JavaScript Developer

sexta-feira, setembro 29, 2006

Outros objetos Built-In

Olá meus queridos leitores.
Hoje vamos continuar nossos estudos pelos objetos Built-In e finaliza-los!

Lembrando, eu não cobri todos os objetos Built-In, eu cobri os principais e mais usados. Hoje vamos ver os próximos, let's go!

Objeto Date
Como o nome diz, o objeto Date serve para trabalhar com datas em JavaScript, vamos ao primeiro exemplo:

var d = new Date();
alert(d.toString());


Iniciando o objeto Date sem usar parâmetros nós pegamos a data atual do computador do cliente, usando o toString() conseguimos a data no formato GMT.
Vamos agora a um caso mais expecífico:

var d = new Date();

alert(d.getFullYear()); //ano
alert(d.getMonth()); //mes
alert(d.getDate()); //dia
alert(d.getHours()); //hora
alert(d.getMinutes()); //minutos
alert(d.getSeconds()); //segundos
alert(d.getMilliseconds()); //mili segundos
alert(d.getDay()); //dia da semana


Como visto acima, podemos pegar separadamente cada parte do tempo. O objeto Date é apenas isso mesmo, um problema muito normal é quando a pessoa quer fazer um calendário, o problema é que o JavaScript não da suporte nativo para dizer quantos dias tem o mês atual, mas isso não é nada que não possamos implementar:

Date.prototype.getMonthDays = function() {
var days = [31, 0, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

var bisexto = false;
var ano = this.getFullYear();

if ((((ano % 4) == 0) && ((ano % 100) != 0)) || ((ano % 400) == 0)) {
bisexto = true;
}

days[1] = bisexto ? 29 : 28;

var mes = this.getMonth();

return days[mes];
}

var d;
d = new Date();
alert(d.getMonthDays());
d = new Date(2006, 1, 12);
alert(d.getMonthDays());
d = new Date(2006, 0, 3);
alert(d.getMonthDays());


Percebam que podemos criar um objeto date informando a data para o objeto, isso é muito útil em caléndarios principalmente. Uma observação importante é que os mesês começam em 0 e não em 1, então 0 é janeiro, 1 é fevereiro...
Prontinho, agora ao usarmos o método getMonthDays teremos como retorno a quantidade de dias do mês, até que nem foi dificil.

Para terminar, vamos criar um relógio digital usando JavaScript, iremos usar um pouco de DOM dessa vez que já é pra dar um gostinho do próximo artigo (que será sobre DOM):

<html>
<head>
<title>Relógio Virtual - JavaScript Developer</title>
<script type="text/javascript">
var updateTime = function() {
var obj = document.getElementById('relogio');
var date = new Date();
var dateString = date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds();

obj.innerHTML = dateString;
setTimeout(updateTime, 1000);
};

window.onload = updateTime;
</script>
</head>
<body>
<div id="relogio"></div>
</body>
</html>


Sem miraculosidades, a função updateTime pega uma referência para o DIV com id relógio (usando o document.getElementById(), vamos ver isso melhor na próxima aula), depois pega a data atual, cria uma string com a hora atual, troca o conteúdo da DIV (usando a propriedade innerHTML) e finalmente manda que ela seja executada novamente após 1 segundo (usando setTimeout()).
Isso é tudo que eu tenho a dizer sobre o objeto Date, vamos ao próximo.

Referência do objeto Date:

Date (Built-in Object)
The Date object provides a wide variety of methods for manipulating dates and times. It is important to remember that Date instances do not contain a “ticking clock” but rather hold a static date value. Internally, the date is stored as the number of milliseconds since the epoch (midnight of January 1, 1970 UTC). This accounts for the prominent role of milliseconds in many Date methods.

Milliseconds, seconds, minutes, hours, and months are enumerated beginning with zero; so, for example, December is month 11. Days are enumerated beginning with 1. Years should always be given using four digits. Modern implementations permit years as much as several hundred thousand years in the past or future, although older implementations often have trouble handling dates before 1970. Many implementations have trouble handling dates before 1 A.D.

Note that Universal Coordinated Time (UTC) is the same as Greenwich Mean Time (GMT).

Constructor
var instanceName = new Date();

var instanceName = new Date(milliseconds);

var instanceName = new Date(stringDate);

var instanceName = new Date(year, month, day [, hrs [, mins [, secs [, ms]]]]);

The first constructor syntax creates a new Date instance holding the current date and time. The second syntax creates an instance holding the date given by the number of milliseconds given in the numeric milliseconds argument. The third syntax attempts to create an instance by converting the string stringDate into a valid date using the parse() method (see under the “Methods” section). The fourth syntax creates an instance according to its numeric arguments. If the optional parameters are omitted, they are filled with zero.

Properties
constructor Reference to the constructor object, which created the object. (IE4+ (JScript 2.0+), MOZ, N3+ (JavaScript 1.1+), ECMA Edition 1)

prototype Reference to the object’s prototype. (IE4+ (JScript 2.0+), MOZ, N3+ (JavaScript 1.1+), ECMA Edition 1)

Methods
getDate() Returns a numeric value indicating the day of the month (1-based). (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+), ECMA Edition 1)

getDay() Returns a numeric value indicating the day of the week (0 for Sunday, 1 for Monday, and so on). (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+), ECMA Edition 1)

getFullYear() Returns a numeric value indicating the four-digit year. (IE4+ (JScript 3.0+), MOZ, N4.06+ (JavaScript 1.3+), ECMA Edition 1)

getHours() Returns a numeric value indicating the hours since midnight (0-based). (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+), ECMA Edition 1)

getMilliseconds() Returns a numeric value indicating the number of milliseconds (0-999). (IE4+ (JScript 3.0+), MOZ, N4.06+ (JavaScript 1.3+), ECMA Edition 1)

getMinutes() Returns a numeric value indicating the number of minutes (0–59). (IE4+ (JScript 3.0+), MOZ, N2+ (JavaScript 1.0+), ECMA Edition 1)

getMonth() Returns a numeric value indicating the number of months since the beginning of the year (0–11; 0 is January). (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+), ECMA Edition 1)

getSeconds() Returns a numeric value indicating the number of seconds (0–59). (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+), ECMA Edition 1)

getTime() Returns a numeric value indicating the number of milliseconds since the epoch. Dates before the epoch return a negative value indicating the number of milliseconds before the epoch. (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+), ECMA Edition 1)

getTimezoneOffset() Returns a numeric value indicating the difference in minutes between the local time and the UTC. Positive values indicate the local time is behind UTC (for example, in the United States) and negative values indicate the local time is ahead of UTC (for example, in India). (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+), ECMA Edition 1)

getUTCDate() Returns a numeric value indicating the day of the month (1-based) using UTC. (IE4+ (JScript 3.0+), MOZ, N4.06+ (JavaScript 1.3+), ECMA Edition 1)

getUTCDay() Returns a numeric value indicating the day of the week (0 for Sunday, 1 for Monday, and so on) according to UTC. (IE4+ (JScript 3.0+), MOZ, N4.06+ (JavaScript 1.3+), ECMA Edition 1)

getUTCFullYear() Returns a numeric value indicating the four-digit year according to UTC. (IE4+ (JScript 3.0+), MOZ, N4.06+ (JavaScript 1.3+), ECMA Edition 1)

getUTCHours() Returns a numeric value indicating the hours since midnight (0-based) according to UTC. (IE4+ (JScript 3.0+), MOZ, N4.06+ (JavaScript 1.3+), ECMA Edition 1)

getUTCMilliseconds() Returns a numeric value indicating the number of milliseconds (0–999) according to UTC. (IE4+ (JScript 3.0+), MOZ, N4.06+ (JavaScript 1.3+), ECMA Edition 1)

getUTCMinutes() Returns a numeric value indicating the number of minutes (0–59) according to UTC. (IE4+ (JScript 3.0+), MOZ, N4.06+ (JavaScript 1.3+), ECMA Edition 1)

getUTCMonth() Returns a numeric value indicating the number of months since the beginning of the year (0–11; 0 is January) according to UTC. (IE4+ (JScript 3.0+), MOZ, N4.06+ (JavaScript 1.3+), ECMA Edition 1)

getUTCSeconds() Returns a numeric value indicating the number of seconds (0–59) according to UTC. (IE4+ (JScript 3.0+), MOZ, N4.06+ (JavaScript 1.3+), ECMA Edition 1)

getYear() Returns the current year minus 1900 or in some cases a four-digit year if the year is greater than 1999. This method is deprecated; use getFullYear() instead. (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+), ECMA Edition 1)

getVarYear() Returns the VT_DATE corresponding to the object. For use with interaction with COM or VBScript, but in general should be avoided. (IE4+ (JScript 3.0+))

parse(stringDate) Attempts to parse the date given in the string stringDate and if successful returns the number of milliseconds of the date relative to the epoch. Valid strings are given in Chapter 7 but in general can be any common representation of a date, for example "month/day/year", "month day, year", or "month day, year hh:mm:ss". Unambiguous shorthand (for example, "Dec" for December) is permitted. If the date cannot be parsed, NaN is returned. (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+), ECMA Edition 1, Static)

setDate(dayOfMonth) Sets the day of the month (1-based) in local time as given by the numeric parameter dayOfMonth. (IE4+ (JScript 3.0+), MOZ, N2+ (JavaScript 1.0+), ECMA Edition 1)

setFullYear(year [, month [, day]]) Sets the date to the year given in the numeric argument year in local time. If the numeric parameters month and day are passed, the month (0-based) and day of the month (1-based) are set as well. If month is greater than 11, the year is incremented accordingly. If day is greater than the number of days in the month, the month is incremented accordingly. (IE4+ (JScript 3.0+), MOZ, N4.06+ (JavaScript 1.3+), ECMA Edition 1)

setHours(hours [, mins [, secs [, ms]]]) Sets the hours (0-based) to the numeric argument given in hours in local time. If the optional parameters are passed, the minutes, seconds, and milliseconds are set accordingly. If any of the parameters is greater than the normal range of values, the date is adjusted accordingly (for example, 60 seconds increments the minutes by one and sets the seconds to zero). (IE4+ (JScript 3.0+), MOZ, N2+ (JavaScript 1.0+), ECMA Edition 1)

setMilliseconds(ms) Sets the milliseconds (0-based) to the numeric argument ms in local time. If ms is greater than 999, the seconds are adjusted accordingly. (IE4+ (JScript 3.0+), MOZ, N4.06+ (JavaScript 1.3+), ECMA Edition 1)

setMinutes(minutes [, secs [, ms]]) Sets the minutes (0-based) to the numeric argument minutes in local time. If numeric arguments secs and ms are supplied, the seconds and milliseconds are set to these values. If any argument is greater than the normal range, appropriate values are incremented accordingly (for example, if secs is 60, the minute is incremented by one and the seconds set to zero). (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+), ECMA Edition 1)

setMonth(month [, day]) Sets the month (0-based) to the numeric argument month in local time. If the numeric argument day is supplied, the day of the month (1-based) is set accordingly. If either value is outside of the expected range, the date is adjusted accordingly (for example, if month is 12 the year is incremented and the month is set to zero). (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+), ECMA Edition 1)

setSeconds(seconds [, ms]) Sets the seconds (0-based) to the numeric argument seconds in local time. If numeric argument ms is supplied, the milliseconds (0-based) are set accordingly. If either value is outside the expected range, the date is adjusted accordingly (for example, if ms is 1000, then the seconds are incremented and milliseconds set to 0). (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+), ECMA Edition 1)

setTime(ms) Sets the date to the date given by the number of milliseconds since the epoch given in ms. Negative values of ms specify dates before the epoch. (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+), ECMA Edition 1)

setUTCDate(dayOfMonth) Sets the day of the month (1-based) in UTC as given by the numeric parameter dayOfMonth. (IE4+ (JScript 3.0+), MOZ, N4.06+ (JavaScript 1.3+), ECMA Edition 1)

setUTCFullYear(year [, month [, day]]) Sets the date to the year given in the numeric argument year in UTC. If the numeric parameters month and day are passed, the month (0-based) and day of the month (1-based) are set as well. If month is greater than 11, the year is incremented accordingly. If day is greater than the number of days in the month, the month is incremented accordingly. (IE4+ (JScript 3.0+), MOZ, N4.06+ (JavaScript 1.3+), ECMA Edition 1)

setUTCHours(hours [, mins [, secs [, ms]]]) Sets the hours (0-based) to the numeric argument given in hours in UTC. If the optional parameters are passed, the minutes, seconds, and milliseconds are set accordingly. If any of the parameters is greater than the normal range of values, the date is adjusted accordingly (for example, a value of 60 seconds increments the minutes by one and sets the seconds to zero). (IE4+ (JScript 3.0+), MOZ, N4.06+ (JavaScript 1.3+), ECMA Edition 1)

setUTCMilliseconds(ms) Sets the milliseconds (0-based) to the numeric argument ms in UTC. If ms is greater than 999, the seconds are adjusted accordingly. (IE4+ (JScript 3.0+), MOZ, N4.06+ (JavaScript 1.3+), ECMA Edition 1)

setUTCMinutes(minutes [, secs [, ms]]) Sets the minutes (0-based) to the numeric argument minutes in UTC. If numeric arguments secs and ms are supplied, the seconds and milliseconds are set to these values. If any argument is greater than the normal range, appropriate values are incremented accordingly (for example, if secs is 60, the minute is incremented by one and the seconds set to zero). (IE4+ (JScript 3.0+), MOZ, N4.06+ (JavaScript 1.3+), ECMA Edition 1)

setUTCMonth(month [, day]) Sets the month (0 based) to the numeric argument month in UTC. If the numeric argument day is supplied, the day of the month (1-based) is set accordingly. If either value is outside of the expected range, the date is adjusted accordingly (for example, if month is 12, the year is incremented and the month is set to zero). (IE4+ (JScript 3.0+), MOZ, N4.06+ (JavaScript 1.3+), ECMA Edition 1)

setUTCSeconds(seconds [, ms]) Sets the seconds (0-based) to the numeric argument seconds in UTC. If numeric argument ms is supplied, the milliseconds (0-based) are set accordingly. If either value is outside the expected range, the date is adjusted accordingly (for example, if ms is 1000, then the seconds are incremented and milliseconds set to 0). (IE4+ (JScript 3.0+), MOZ, N4.06+ (JavaScript 1.3+), ECMA Edition 1)

setYear(year) This method is deprecated; use setFullYear() instead. Sets the year to the numeric value year in local time. The year parameter must be the desired year minus 1900. (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+), ECMA Edition 1)

toGMTString() This method is deprecated; use toUTCString() instead. Returns the string representation of the date relative to GMT. (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+), ECMA Edition 1)

toLocaleString() Returns the date converted to a string formatted according to local conventions as defined by the operating system. For example, the U.S. uses month/day/year whereas Europe uses day/month/year. The return value is not to be used for computation, but rather for display to the user. (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+), ECMA Edition 1)

toString() Returns the date as a string. (IE4+ (JScript 2.0+), MOZ, N3+ (JavaScript 1.1+), ECMA Edition 1)

toUTCString() Returns the date formatted as a string according to UTC. (IE4+ (JScript 3.0+), MOZ, N4.06+ (JavaScript 1.3+), ECMA Edition 1)

UTC(year, month, day [, hours [, mins [, secs [, ms]]]]) This static method returns a numeric value indicating the number of milliseconds between the epoch and the date given by the numeric parameters. Any parameters outside of their expected range cause the date to be adjusted accordingly. (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+), ECMA Edition 1)

valueOf() Returns a numeric value indicating the number of milliseconds difference between the date and the epoch. (IE4+ (JScript 2.0+), MOZ, N3+ (JavaScript 1.1+), ECMA Edition 1)

Support
Supported in IE3+ (JScript 1.0+), Mozilla, N2+ (JavaScript 1.0+), ECMAScript Edition 1.

Notes
The Date object is seriously broken in older browsers. The authors suggest avoiding its use except in the most basic tasks in browsers earlier than IE4 and Netscape 4.

The Date object cannot be enumerated directly using for/in.


Objeto Global

Esse é o objeto mais desconhecido e conhecido ao mesmo tempo, muitos usam ele e nem sabem da sua existência.
O objeto Global é um objeto estático (não pode ser instanciado, você não pode fazer: a = new Global()), e assim só tem métodos estáticos. O objeto global pode ser acesso de qualquer lugar, é até meio complicado falar dele, pois ele não tem nada específico, então eu prefiro falar diretamente de suas constates e métodos:

método eval

Esse talvez sejá o método mais conhecido do objeto Global, muitos que ja mexeram com JavaScript devem te-lo usado.
Para quem não conhece, o eval consegue pegar um string, e executa-la como se fosse código, exemplo:

var a = "alert('codigo a ser executado por eval')";
eval(a);


A variável a contém dentro dela uma string, e o eval executa essa string como se fosse código, veremos bem sua utilidade ao estudar-mos Ajax, pois o melhor padrão atual para transferencia de dados (o JSON), usa diretamente o eval para ler o conteudo.

método parseInt

O método parseInt converte uma string em número, exemplo:

var a = '5';
var b = '6';

alert(a + b);
alert(parseInt(a) + parseInt(b));


constantes

Infinity - contem um valor de infinito (um número quando ultrapassa o limite do javascript)
NaN - Not a Number, constante para calculos erroneos que não retornaram um número
undefined - para variáveis indefinidas

Isso é o principal do Global, o resto eu deixo pela referência:

Global (Built-in Object)
The Global object provides methods and constants that can be used freely anywhere in your scripts. Global is defined to be the globally enclosing context, so this object cannot be instantiated or even directly accessed; its properties and methods are always within the scope of an executing script. Its sole purpose is as a catch-all for globally available methods and constants.

Constructor
This object cannot be instantiated because it defines the global context and thus has no constructor.

Properties
Infinity Constant holding the numeric value Infinity. (IE4+ (JScript 3.0+), N4.06+ (JavaScript 1.3+), MOZ, ECMA Edition 1)

NaN Constant holding the numeric value NaN (not a number). (IE4+ (JScript 3.0+), N4.06+ (JavaScript 1.3+), MOZ, ECMA Edition 1)

undefined Constant holding the value undefined. (IE5.5+ (JScript 5.5+), N4.06+ (JavaScript 1.3+), MOZ, ECMA Edition 1)

Methods
decodeURI(encodedURI) URI-decodes the string encodedURI and returns the decoded string. (IE5.5+ (JScript 5.5+), MOZ/N6+ (JavaScript 1.5+), ECMA Edition 3)

decodeURIComponent(encodedURI) URI-decodes the string encodedURI and returns the decoded string. (IE5.5+ (JScript 5.5+), MOZ/N6+ (JavaScript 1.5+), ECMA Edition 3)

encodeURI(uri) URI-encodes the string uri, treating uri as a full URI. Legal URI characters (for example, the :// after the protocol) are not encoded. Returns the encoded string. (IE5.5+ (JScript 5.5+), MOZ/N6+ (JavaScript 1.5+), ECMA Edition 3)

encodeURIComponent(uriComponent) URI-encodes the string uriComponent and returns the encoded string. All potentially problematic characters (for example, / and ?) are encoded. (IE5.5+ (JScript 5.5+), MOZ/N6+ (JavaScript 1.5+), ECMA Edition 3)

escape(string) URI-encodes string and returns the encoded string. Using the newer encodeURIComponent() is preferable. (IE3+ (JScript 1.0+), N2+ (JavaScript 1.0+), MOZ)

eval(string) Executes string as JavaScript. (IE3+ (JScript 1.0+), N2+ (JavaScript 1.0+), MOZ, ECMA Edition 1)

isFinite(value) Returns a Boolean indicating if the numeric argument value is finite. Returns false if value is NaN. (IE4+ (JScript 3.0+), N4.06+ (JavaScript 1.3+), MOZ, ECMA Edition 1)

isNaN(value) Returns a Boolean indicating if the numeric argument value is NaN. (IE4+ (JScript 3.0+), N3+ (JavaScript 1.1+), MOZ, ECMA Edition 1)

parseFloat(string) Parses string as a floating-point number and returns its value. If string cannot be converted, NaN is returned. (IE3+ (JScript 1.0+), N2+ (JavaScript 1.0+), MOZ, ECMA Edition 1)

parseInt(string) Parses string as an integer and returns its value. If string cannot be converted, NaN is returned. (IE3+ (JScript 1.0+), N2+ (JavaScript 1.0+), MOZ, ECMA Edition 1)

unescape(encodedString) URI-decodes encodedString and returns the decoded string. Using the newer decodeURIComponent() method is preferable. (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+))

Support
Supported in IE3+ (JScript 1.0+), N2+ (JavaScript 1.0+), Mozilla, ECMAScript Edition 1.


Por hoje é apenas isso, no próximo começaremos o DOM, ai vai ficar mais legal, vamos ver como mexer com elementos html e alguns efeitos simples ;). Até lá.

Só para complementar, quando eu postei sobre objetos eu esqueci de deixar a referência do Object, vou coloca-la abaixo e também vou adiciona-la no post de objetos:

Object (Built-in Object)
Object is the basic object from which all other objects are derived. It defines methods common to all objects that are often overridden to provide functionality specific to each object type. For example, the Array object provides a toString() method that functions as one would expect an array’s toString() method to behave.This object also permits the creation of user-defined objects and instances are quite often used as associative arrays.

Constructor
var instanceName = new Object();

This statement creates a new (generic) object.

Properties
prototype The prototype for the object. This object defines the properties and methods common to all objects of this type. (IE4+ (JScript 3.0+), MOZ, N3+ (JavaScript 1.1+), ECMA Edition 1)

Methods
hasOwnProperty(property) Returns a Boolean indicating whether the object has an instance property by the name given in the string property. (IE5.5+, MOZ/N6+, ECMA Edition 3)

isPrototypeOf(obj) Returns a Boolean indicating if the object referenced by obj is in the object’s prototype chain. (IE5.5+, MOZ/N6+, ECMA Edition 3)

propertyIsEnumerable(property) Returns a Boolean indicating if the property with the name given in the string property will be enumerated in a for/in loop. (IE5.5+, MOZ/N6+, ECMA Edition 3)

toSource() Returns a string containing a JavaScript literal that describes the object. (MOZ, N4.06+ (JavaScript 1.3+))

toString() Returns the object a string, by default "[object Object]". Very often overridden to provide specific functionality. (IE4+ (JScript 3.0+), MOZ, N2+ (JavaScript 1.0+), ECMA Edition 1)

unwatch(property) Disables watching of the object’s property given by the string property. (N4 (JavaScript 1.2))

valueOf() Returns the primitive value associated with the object, by default the string "[object Object]". Often overridden to provide specific functionality. (IE4+ (JScript 3.0+), N3+ (JavaScript 1.1+), ECMA Edition 1)

watch(property, handler) Sets a watch on the object’s property given in string property. Whenever the value of the property changes, the function handler is invoked with three arguments: the name of the property, the old value, and the new value it is being set to. The handler can override the setting of the new value by returning a value, which is set in its place. (N4 (JavaScript 1.2))

Support
Supported in IE4+ (JScript 3.0+), MOZ, N2+ (JavaScript 1.0+), ECMAScript Edition 1.


Todos os objetos do JavaScript contém os métodos e propriedades acima, com raras excessões. Falow!

quinta-feira, setembro 21, 2006

Strings e Expressões Regulares

Boa noite galera, agreço as visitas e os comentários, continuem sempre assim ;).

Como mensionado antes, hoje vou falar sobre Strings e Expressões Regulares, bom, eu não pretendo me fixar no assunto de expressões regulares, eu apenas mostrarei como usa-las no JavaScript, pra quem quizer estudar expressões regulares, acesse esse site: http://guia-er.sourceforge.net/ esse é melhor site sobre expressões regulares que eu conheco, quem quizer estude por ele, pois é muito bom.

Voltando ao nosso assunto, hoje aprenderemos a manusear Strings usando JavaScript, vamos ver inicialmente a criação de strings:

var a = "primeira string";
var b = new String("de outro modo");

alert(a);
alert(b);


Isso é bem simples, como vocês devem saber, strings devem ficar dentro aspas, no JavaScript você pode tanto usar aspas simples como duplas, isso não vai interferir em nada.

Comparação de Strings
Temos que ter uma atenção nessa parte, a comparação de strings pode ser feita usando o operador ==, mas fazer a comparação dessa forma deixa um risco, porque o operador == vai comparar a referência dos objetos, vamos ver em exemplos isso:

var a = "teste";
var b = "teste";

if(a == b)
alert('a e b sao iguais');
else
alert('a e b sao diferentes');

var c = new String("teste");
var d = new String("teste");

if(c == d)
alert('c e d sao iguais');
else
alert('c e d sao diferentes');


Como podem ver, oque acontece é que quanto definimos a e b daquela forma, ele acaba usando strings cacheadas (guardas no mesmo ponto de memória para melhorar o desempenho), ja usando new String com c e d ele força uma nova alocação, assim as refencias ficam diferetes, e acaba que na comparação ele considara as strings diferentes (mesmo o texto sendo exatamente igual). Para resolver isso, fazemos uma coisa meio bizarra, prefiro explicar com codigos:

var a = "teste";
var b = "teste";

if(a == b)
alert('a e b sao iguais');
else
alert('a e b sao diferentes');

var c = new String("teste");
var d = new String("teste");

if(c.toString() == d.toString())
alert('c e d sao iguais');
else
alert('c e d sao diferentes');


Pronto, agora nossa comparação de c com d retornou verdadeira.

Operador de concatenação e caracteres de escape

Para concatenar strings não tem segredo, basta usar o operador de soma:

var a = 'oi';
var b = 'visitante';

alert(a + ' ' + b);


Mas um porém é quando queremos concatenar números, como se fossem strings, para isso temos que concatenar o número a uma string, vamos ver como concatenas dois números:

var a = 5;
var b = 9;

alert(a + '' + b);


Usando uma string, mesmo que seja vazia, ao somar com um número ele transforma aquele número em uma string, assim temos a concatenção e não a soma dos números.

Caracteres de escape são caracteres que existem mas não são vistos exatamente, como por exemplo o enter, para as pessoas o enter é um separador de linha, para o computador é apenas mais um caractere, para escrever uma linha do windows (que usa 2 caracateres) escreveriamos "\r\n" que para o JavaScript o \r eh transformado em um caractere, e o \n em outro, isso forma uma linha no windows, em muitos casos podemos usar apenas o \n, pois ele ja resolver, vamos ver a tabela dos caracteres escapados no JavaScript:






















Caractere Resultado
\n nova linha
\r retorno de carro
\t tabulação
\\ insere uma barra


Existem mais, mas esses são os mais usados. Como as strings sao representadas dentro de aspas, as vezes precisamos usar essas aspas dentro da string, para isso usamos o escape \" ou \' dependendo do seu caso, vamos ver um exemplo:

alert("texto em \"aspas\"");
alert('texto em \'aspas\'');


Métodos de String

As Strings do JavaScript não tem tantos métodos quanto precisamos hoje em dia, ela tem os mais básicos, por isso muitas pessoas fazem uma implementação de extensão para as strings (usando seu prototype e adicionando mais recursos), em artigos futuros faremos uma implementação desse gênero, adicionando vários recursos. Mas o JavaScript tem seus recursos, então vamos conhece-los:

Quando precisamos pegar um caractere expecífico em uma string, usamos o método charAt:

var a = "abcde";

alert(a.charAt(1));
alert(a.charAt(4));


Lembre-se sempre que a indexção começa em zero, entao o primeiro caractere é o zero, o segundo é um e por ai vai.

Muito parecido com o charAt temos o charCodeAt que funciona da mesma maneira, mas no lugar de retornar o caractere, ele retorna um número inteiro, que no caso é o codigo ASCII do caractere (quem quizer, acesse http://www.asciitable.com/ para ver a tabela completa).

Um método que vai um pouco além do charAt é o método substring, esse método pega um bloco da string:

var a = "abcde";

alert(a.substring(0, 2));
alert(a.substring(1, 4));


O primeiro argumento é a posição inicial, o segundo a posição final.

Quando precisamos procurar uma string dentro da outra, usamos o método indexOf, esse método aceita uma string como argumento, e procura essa string dentro da string original, se encontrado retorna a posição onde foi encontrado, caso contrário retorna -1.

var a = "abcde";

alert(a.indexOf("b"));
alert(a.indexOf("e"));
alert(a.indexOf("cd"));
alert(a.indexOf("z"));


Também é possivel passar um segundo argumento, que indica a posição inicial da busca (sinta-se livre para testar). Inverso ao indexOf que busca a partir do início da string, existe o método lastIndexOf que procura do início para o começo da string.

Esse não é o melhor método para buscar algo dentro de uma string, o melhor é usar expressões regulares (veremos isso mais adiante), mas para casos mais simples, o indexOf resolve muitas coisas.

O último método que veremos, é o método split, esse método "quebra" uma string em um array, usando uma string para realizar essa quebra (fazendo a separação):

var a = "isso seria uma simples frase";
var b = a.split(' '); //separando por espacos

for(var i = 0; i < b.length; i++) {
alert(b[i]);
}


Esses foram os métodos principais para tratamento de string no JavaScript, não menos importante, temos a propriedade length (isso, mesmo nome que tem no Array), o length retorna a quantidade de caracteres que existem na string.

var a = "abc";
var b = "abcde";
var c = "uma string cheia de caracteres";

alert(a.length);
alert(b.length);
alert(c.length);


Expressões Regulares

As expressões regulares são a parte mais interessante da área de strings (pelo menos pra mim). Com expressões regulares você consegue facilmente validar strings, coisas que precisariam de um grande código se fossem feitas de outra maneira (como usando substrings e indexOf).

O JavaScript tem um objeto chamado RegExp que cuida dessa parte, existe o meio onde você cria um RegExp e valida uma string a partir dele, ou você pode usar um método da string (que é o match) para usar um RegExp para validar, no final tudo gera o mesmo resultado. Vamos ver como validar uma data usando RegExp (vamos ver usando os 2 processos que eu disse):

var dataValidator = new RegExp("^\\d{2}/\\d{2}/\\d{4}$");

if(dataValidator.test('15/06/2006'))
alert('Data válida');
else
alert('Data inválida');

if(dataValidator.test('158/06/2006'))
alert('Data válida');
else
alert('Data inválida');

if('15/06/2006'.match(dataValidator))
alert('Data válida');
else
alert('Data inválida');

if('158/06/2006'.match(dataValidator))
alert('Data válida');
else
alert('Data inválida');


Esse validador diz que a string deve ter 2 digitos numericos (\d{2}), depois uma barra, mais dois digitos numericos, depois outra barra, e finalmente 4 digitos numericos. Também informamos que a string deve ser exatamente isso (usando o ^ no início e $ no final), o digito ^ diz que a string deve comecar daquele jeito, e o $ diz que a string deve acabar daquele jeito. Como eu disse antes, não vou parar para explicar as expressões regulares pois isso está fora do meu contexto.

Além de validar, as vezes queremos pegar alguns pedaços da string, por exemplo, se a partir dessa string de mes, quizesse-mos pegar apenas o mês (que seriam os 2 dígitos do meio), com expressões regulares isso se torna facil, vamos ver isso no exemplo a seguir, e também vamos ver outro meio de iniciar expressões regulares:

var dataValidator = /^\d{2}\/(\d{2})\/\d{4}$/;
var data = '15/12/2005';
var grupos;

if(grupos = data.match(dataValidator)) {
alert('Mes: ' + grupos[1]);
}


Percebam o novo modo de criação, você só precisa colocar uma / e depois outra para finalizar, a expressão fica dentro das barras, quando é preciso inserir / dentro da expressão usamas \/ assim estamos "escapando" a barra. Outra observação é que colocamos a parte da expressão que pega o mês entre parênteses, assim podemos recupera-la depois. Além de validar, o método match retorna um array com os grupos que foram marcados dentro da expressão, o índice zero contém a string inteira, e a partir do um tem os grupos marcados (na mesma ordem em que foram marcados na string).

Também podemos fazer substituições usando expressões regulares, por exemplo:

var string = 'mariazinha, joaninha, pedrinho';
var novaString = string.replace(/(zinh(a|o)|inh)/g, '');

alert(novaString);


No caso substituimos as ocorrências expressão por nada :P. Notem agora o uso de uma letra "g" no final da expressão, essa letra "g" indica que mesmo após uma ocorrencia, ele deve continuar buscando a expressão na string, se você remover essa letra ele só vai substituir o nome de mariazinha. Fora a letra g temos a letra i que torna a expressão case-insensitive (não diferencia maiúsculas de minúsculas) e a letra m que faz buscas multi-linha.

Por hoje é só pessoal, espero ter conseguido passar o básico de strings e uso de expressões regulares em JavaScript, estudem expressões regulares pelo site que eu passei no início do artigo, vocês vão ver coisas realmente interessantes, estudem la e vão testando a aplicação das mesmas com o JavaScript, assim vocês pegam um "2 em 1" ;)

Antes de ir, sempre aquela boa referência:

Classe String

String (Built-in Object)
String is the container object for the primitive string data type. It supplies methods for the manipulation of strings in addition to those that create traditional HTML markup from plain text. When manipulating strings, remember that like all JavaScript indices, the enumeration of character positions begins with zero.

Constructor
var instanceName = new String(initialValue);

where initialValue is a string. Omitting initialValue creates a String where value is the empty string ("").

Properties
length Integer indicating the number of characters in the string. (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+), ECMA Edition 1)

prototype Reference to the object’s prototype. (IE4+ (JScript 2.0+), MOZ, N3+ (JavaScript 1.1+), ECMA Edition 1)

Methods
anchor(name) Returns the string marked up as an HTML anchor (<a name="name">

string value</a>). (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+), ECMA Edition 1).

big() Returns the string marked up as big HTML text (<big>string value</big>). (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+))

blink() Returns the string marked up as blinking HTML text (<blink>string value</blink>). (IE3+ (JScript 1.0+), N2+ (JavaScript 1.0+), MOZ)

bold() Returns the string marked up as bold HTML text (<bold>string value</bold>). (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+))

charAt(position) Returns a string containing the character at index position in the string. The empty string is returned if position is out of range. (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+), ECMA Edition 1)

charCodeAt(position) Returns an unsigned integer representing the Unicode value of the character at index position. If position is out of range, NaN is returned. (IE5.5+ (JScript 5.5+), MOZ, N4+ (JavaScript 1.2+), ECMA Edition 1)

concat(string2 [, string3 [, ... ]]) Returns the string obtained by concatenating the current string value with string2, string3, .... (IE4+ (JScript 3.0+), MOZ, N4+ (JavaScript 1.2+), ECMA Edition 1)

fixed() Returns the string marked up as fixed-width HTML text (<tt>string value</tt>). (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+))

fontcolor(theColor) Returns the string marked up as colored HTML according to the string color (<font color="theColor">string value</font>). (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+))

fontsize(theSize) Returns the string marked up according to the HTML font size given in theSize (<font size="theSize">string value</font>). HTML font sizes are 1 through 7, or relative +/– 1–6. (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+))

fromCharCode(char0 [, char1 [, ...]]) Creates a string from the given characters. The arguments char0, char1, ... are Unicode numbers corresponding to the desired characters. (IE4+ (JScript 3.0+), MOZ, N4+ (JavaScript 1.2+), ECMA Edition 1, Static)

indexOf(searchString [, startIndex]) Returns the index of the first occurrence of searchString in the string. If startIndex is specified, then the first occurrence after index startIndex is returned. If searchString is not found, –1 is returned. (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+), ECMA Edition 1)

italics() Returns the string marked up as italicized HTML text (<i>string value</i>). (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+))

lastIndexOf(searchString [, startIndex]) Returns the index of the last occurrence of searchString in the string. If startIndex is specified, the index of the last occurrence starting at index startIndex or before is returned. If searchString is not found, –1 is returned. (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+), ECMA Edition 1)

link(theHref) Returns the string marked up as an HTML link to the string theHref (<a href="theHref">string value</a>). (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+))

match(regexp) Executes a regular expression match with the regular expression regexp and returns an array of results. If no match is found, null is returned. Otherwise, the returned array is exactly like that returned by RegExp.exec(). (IE4+ (JScript 3.0+), MOZ, N4+ (JavaScript 1.2+), ECMA Edition 3)

replace(regexp, replacement) Returns the string obtained by executing a match with the regular expression regexp on the string and then replacing each piece of matching text with the string replacement. In IE5.5 and N4.06+ replacement can be a function (see full description at MSDN). (IE3+ (JScript 1.0+), MOZ, N4+ (JavaScript 1.2+), ECMA Edition 3)

search(regexp) Executes a regular expression match with regular expression regexp and returns the index of the beginning of the matching text in the string. If no match is found, –1 is returned. (IE4+ (JScript 3.0+), MOZ, N4+ (JavaScript 1.2+), ECMA Edition 3)

slice(start [, end]) Returns a new string containing the substring from index start up to but not including index end. If end is omitted, the substring returned runs to the end of the string. If start or end is negative, it is treated as an offset from the end of the string. (IE4+ (JScript 3.0+), MOZ, N2+ (JavaScript 1.0+), ECMA Edition 3)

small() Returns the string marked up as small HTML text (<small>string value</small>). (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+))

split([separator [, limit]]) Returns the array of strings obtained by splitting the string at each occurrence of separator (which may be a string or regular expression). The separator is not included in the array returned. If no separator is given, the string is split into an array of strings holding its individual characters. If the integer limit is given, only the first limit parts are placed in the array. (IE4+ (JScript 3.0+), MOZ, N3+ (JavaScript 1.1+), ECMA Edition 1)

strike() Returns the string marked up as struck-through HTML text (<strike>string value</strike>). (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+))

sub() Returns the string marked up as subscript HTML text (<sub>string value</sub>). (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+))

substr(start [, length]) Returns a new string containing a substring of length length beginning at index start. If length is not given, the substring returned runs to the end of the string. (IE4+ (JScript 3.0+), MOZ, N2+ (JavaScript 1.0+))

substring(start [, end]) Returns a new string containing the substring running from index start up to but not including index end. If end is not given, the substring runs to the end of the string. If start is greater than end, the values are swapped. (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+), ECMA Edition 1)

sup() Returns the string marked up as superscript HTML text (<sup>string value</sup>). (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+))

toLowerCase() Returns the string converted to all lowercase. (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+), ECMA Edition 1)

toUpperCase() Returns the string converted to all uppercase. (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+), ECMA Edition 1)

Support
Supported in IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+), ECMAScript Edition 1.

Notes
This object does not operate on values in place. That is, when manipulating a String with one of its methods, the method returns the result of the operation. It does not change the value of the String that it was invoked as a method of. You can, of course, use self-assignment to this effect—for example,

var mystring = mystring.toUpperCase()

The String methods do not produce XHTML style markup.


Classe RegExp

RegExp (Built-in Object)
Instances of RegExp objects hold regular expression patterns and provide the properties and methods that enable their use on strings. In addition, each window has a RegExp object that provides static (class) properties giving information about the most recent match that was executed. These properties are dynamically scoped.

Constructor
var instanceName = new RegExp(expr [, flags]);

where expr is a string containing a regular expression (for example, "abc.*") and flags is an optional string denoting the flags for the expression (for example, "gi").

Properties
$1, $2, ... $9 The $n property contains the string corresponding to the nth parenthesized subexpression of the most recently executed match. The properties are read-only. (IE4+ (JScript 3.0+), MOZ, N4+ (JavaScript 1.2+))

global A read-only Boolean indicating whether the global flag ("g") was used to create the regular expression. (IE5.5+ (JScript 5.5+), MOZ, N4+ (JavaScript 1.2+), ECMA Edition 3)

ignoreCase A read-only Boolean indicating whether the case-insensitive flag ("i") was used to create the regular expression. (IE5.5+ (JScript 5.5+), MOZ, N4+ (JavaScript 1.2+), ECMA Edition 3)

index A read-only integer value indicating the character position where the first successful match begins (during the most recently executed match). (IE4+ (JScript 3.0+))

input Holds the string upon which the most recent regular expression match was conducted. This property is not automatically filled in N6. (IE4+ (JScript 3.0+), MOZ, N4+ (JavaScript 1.2+))

lastIndex Integer specifying the character index of the string at which the next match will begin. Used during global matching. (IE4+ (JScript 3.0+), MOZ, N4+ (JavaScript 1.2+), ECMA Edition 3)

lastMatch A read-only string containing the last matched characters of the most recent match. (IE5.5+ (JScript 5.5+), MOZ, N4+ (JavaScript 1.2+))

lastParen A read-only string containing the last matched parenthesized subexpression (of the most recent match). (IE5.5+ (JScript 5.5+), MOZ, N4+ (JavaScript 1.2))

leftContext A read-only substring up to but not including the beginning of the most recently matched text (of the most recently executed match). (IE5.5+ (JScript 5.5+), MOZ, N4+ (JavaScript 1.2))

multiline A read-only Boolean indicating whether the multiline flag ("m") was used to create the regular expression. (IE5.5+ (JScript 5.5+), MOZ, N4+ (JavaScript 1.2+), ECMA Edition 3)

prototype Reference to the object’s prototype. (IE4+ (JScript 3.0+), MOZ, N4+ (JavaScript 1.2+), ECMA Edition 3)

rightContext A read-only substring following (but not including) the most recently matched text. (IE5.5+ (JScript 5.5+), MOZ, N4+ (JavaScript 1.2), ECMA Edition 3)

source A read-only string containing the text that makes up the pattern (excluding any slashes used to define it and the flags). (IE4+ (JScript 3.0+), MOZ, N4+ (JavaScript 1.2), ECMA Edition 3)

Methods
compile(expr [, flags]) Compiles the regular expression expr with flags flags in the object. Used to replace an expression with a new one. (IE4+ (JScript 3.0+), MOZ, N4+ (JavaScript 1.2), ECMA Edition 3)

exec(str) Executes a match against the string str and returns an array containing the results. If no match was made, null is returned. If str is omitted, the contents of RegExp.input is used as str. The resulting array has the entire match in element zero, and any matched subexpressions at subsequent indices. It also has instance properties input (which holds the string on which the match was executed), index (which holds the index of the beginning of the match in the input string), and in IE lastIndex (which holds the index of the first character following the match). (IE4+ (JScript 3.0+), MOZ, N4+ (JavaScript 1.2), ECMA Edition 3)

test(str) Returns a Boolean indicating whether the regular expression matches a part of the string str. (IE4+ (JScript 3.0+), MOZ, N4+ (JavaScript 1.2), ECMA Edition 3)

toString() Returns the string corresponding to the regular expression, including enclosing slashes and any flags that were used to define it. (IE4+ (JScript 3.0+), MOZ, N4+ (JavaScript 1.2), ECMA Edition 3)

Support
Supported in IE4+ (JScript 3.0+), MOZ, N4+ (JavaScript 1.2+), ECMAScript Edition 3.


Vou indo, no próximo artigo eu falarei sobre outros objetos Built-In, depois dele já começaremos a parte legal do JavaScript, me suportem até lá, vai valer a pena ;)

sexta-feira, setembro 15, 2006

Arrays

Agora vamos começar a estudar os objetos built-in do JavaScript, vamos comecar com um objeto muito importante, o objeto Array.

Como vocês devem saber, o Array é uma estrutura de dados, no JavaScript essa é a única estrutura existente (por padrão), os arrays do JavaScript só podem ter índices númericos, na verdade você até pode usar índices associativos, mas na verdade você estará modificando o objeto e não colocando um dado no array. Vamos ver alguns exemplos simples de arrays no JavaScript.

var nomes = new Array();
nomes[0] = 'Maria';
nomes[1] = 'Joao';
nomes[2] = 'Ana';

for(var i = 0; i < nomes.length; i++) {
alert(nomes[i]);
}


Fizemos um simples array, colocamos uma string em cada item do nosso array colocamos uma string, depois fizemos um for que percorre os itens do nosso array. Note o uso da variável length do array, essa variável nos retorna a quantidade atual de itens no array. Vamos ver outras formas para criar esse mesmo array:

var nomes = [];
nomes[0] = 'Maria';
nomes[1] = 'Joao';
nomes[2] = 'Ana';

for(var i = 0; i < nomes.length; i++) {
alert(nomes[i]);
}


var nomes = ['Maria', 'Joao', 'Ana'];

for(var i = 0; i < nomes.length; i++) {
alert(nomes[i]);
}


var nomes = new Array('Maria', 'Joao', 'Ana');

for(var i = 0; i < nomes.length; i++) {
alert(nomes[i]);
}


var nomes = [];
nomes.push('Maria');
nomes.push('Joao');
nomes.push('Ana');

for(var i = 0; i < nomes.length; i++) {
alert(nomes[i]);
}


Agora eu mostrei que podemos substituir o new Array() por [], eles funcionam da mesma maneira, use o de sua preferência. Também vimos que é possivel inicializar um array já com valores, quando sabemos os valores isso é util, mas na maioria dos casos nós precisamos sair colocando valores ao longo do tempo, usando o método push do array, nós inserimos um valor no final do array, podemos inserir varios valores usando apenas um push, como veremos abaixo:

var nomes = [];
nomes.push('Maria', 'Joao', 'Ana');

for(var i = 0; i < nomes.length; i++) {
alert(nomes[i]);
}


Os arrays do JavaScript são bastante dinâmicos, o mesmo array pode ter valores numéricos, strings, objetos e outros, tudo num mesmo array, o JavaScript não faz distinção. Os arrays em JavaScript tem métodos úteis para podermos usa-lo como uma pilha ou fila por exemplo.

Vou falar rapidamente sobre os métodos mais usados do array:

  • push() - adiciona um ou mais itens ao final do array

  • pop() - retorna e remove o último elemento do array

  • shift() - retorna e remove o primeiro elemento do array

  • unshift() - adiciona um ou mais itens no início do array

  • join() - ele cola todos os elementos do array, usando uma string (passada por parâmetro) como separador, e retorna essa string



Vamos agora construir um programinha simples, que coleta dados de pessoas, armazena esses dados em um array, e depois gera um simples relatório. Vamos explicar melhor o nosso programa:

1 - coleta de dados
Usando o comando prompt do JavaScript, vamos coletar dados de 10 pessoas, os dados coletados serão: nome, idade e sexo.

2 - processamento de dados
Vamos tratar nossos dados e conseguir as informações desejadas, nesse nosso caso, vamos mostrar ao final, o nome do homem mais velho e sua idade, o nome da mulher mais nova e sua idade, quantos homens e quantas mulheres foram entrevistados.

3 - exibicao de dados
Vamos mostrar os dados gerados na tela.

Antes de começar, eu devo dizer que esta não é forma mais simples de fazer esse algorimo, mas minha intenção é mostrar mais recursos do array. Nessa forma, vamos olhar como fazer usando a função sort do array.

A primeira coisa a ser feita, é criar um objeto Pessoa, que vai ser uma estrura que irá guardar os dados de cada entrevistado:

var Pessoa = function(nome, idade, sexo) {
this.nome = nome;
this.idade = idade;
this.sexo = sexo;
};


Bem simples, apenas um objeto que guarda os dados que precisamos. Vamos agora definir as variáveis que farão parte do programa:

var numPessoas = 5;
var homens = [];
var mulheres = [];


A variável numPessoas vai dizer quantas pessoas serão entrevistas, no array homens vamos guardas os entrevistados do sexo masculino, e no array mulheres os do sexo feminino .

Vamos agora fazer a primeira parte, a coleta de dados:

for(var i = 0; i < numPessoas; i++) {
var nome = prompt('Digite o nome:');
var idade = prompt('Digite a idade:');
var sexo = prompt('Digite o sexo (M para masculino, F para feminino):');

idade = parseInt(idade); //convertendo a string em numero
sexo = sexo.toUpperCase(); //convertendo para maiusculo

var p = new Pessoa(nome, idade, sexo);

if(sexo == 'M')
homens.push(p);
else
mulheres.push(p);
}


Pronto, com isso ja teremos os nossos arrays preenchidos. Para usarmos a função sort num objeto como o nosso, precisaremos criar uma função separada que vai definir quando um objeto é superior, inferior ou igual ao outro, vamos criar essa função:

var PessoaIdadeSorter = function(obj1, obj2) {
if(obj1.idade == obj2.idade)
return 0;

return obj1.idade > obj2.idade ? 1 : -1;
};


A função compara a idade das pessoas, e retorna o valor de acordo. Agora basta classificarmos nossos arrays:

homens.sort(PessoaIdadeSorter);
mulheres.sort(PessoaIdadeSorter);


Pronto, nossos arrays já estão classificados por idade, agora é facil terminar, vamos fazer a exibição:

var qtdHomens = homes.length;
var qtdMulheres = mulheres.length;
var homemMaisVelho = homens.pop();
var mulherMaisNova = mulheres.shift();

document.write('Foram entrevistados ' + qtdHomens + ' homens e ' + qtdMulheres + ' mulheres.
');
document.write('O homem mais velho se chama ' + homemMaisVelho.nome + ' com ' + homemMaisVelho.idade + ' anos
');
document.write('A mulher mais nova se chama ' + mulherMaisNova.nome + ' com ' + mulherMaisNova.idade + ' anos
');


Como nossos arrays estão ordenados pela idade, então o homem mais velho é o ultimo elemento do array homens, e a mulher mais nova é o primeiro elemento do array das mulheres.

Vou colocar o código completo abaixo (só pra facilitar):

var Pessoa = function(nome, idade, sexo) {
this.nome = nome;
this.idade = idade;
this.sexo = sexo;
};

var numPessoas = 5;
var homens = [];
var mulheres = [];

for(var i = 0; i < numPessoas; i++) {
var nome = prompt('Digite o nome:');
var idade = prompt('Digite a idade:');
var sexo = prompt('Digite o sexo (M para masculino, F para feminino):');

idade = parseInt(idade); //convertendo a string em numero
sexo = sexo.toUpperCase(); //convertendo para maiusculo

var p = new Pessoa(nome, idade, sexo);

if(sexo == 'M')
homens.push(p);
else
mulheres.push(p);
}

var PessoaIdadeSorter = function(obj1, obj2) {
if(obj1.idade == obj2.idade)
return 0;

return obj1.idade > obj2.idade ? 1 : -1;
};

homens.sort(PessoaIdadeSorter);
mulheres.sort(PessoaIdadeSorter);

var qtdHomens = homes.length;
var qtdMulheres = mulheres.length;
var homemMaisVelho = homens.pop();
var mulherMaisNova = mulheres.shift();

document.write('Foram entrevistados ' + qtdHomens + ' homens e ' + qtdMulheres + ' mulheres.
');
document.write('O homem mais velho se chama ' + homemMaisVelho.nome + ' com ' + homemMaisVelho.idade + ' anos
');
document.write('A mulher mais nova se chama ' + mulherMaisNova.nome + ' com ' + mulherMaisNova.idade + ' anos
');


Com isso eu termino os arrays, vou a referência do objeto Array para quem tiver interesse:

Array (Built-in Object)
Arrays store ordered lists of data. Data is stored at indices enumerated beginning with zero, which are accessed using the array access ([]) operator. Allocation of array memory is handled by the interpreter, so there is no need to explicitly resize arrays to accommodate more data. In addition, arrays are permitted to be sparse, that is, to have “holes” consisting of an arbitrary number of unused indices. Any index that has not been assigned data has value undefined, and the highest index addressable is 232 –1 because indices are converted to unsigned 32-bit integers before use. JavaScript arrays are one-dimensional, but since array elements can be of any type, multidimensional arrays are supported as arrays with elements that are arrays.

You can explicitly remove a value from an array using the delete operator, but there is no way to destroy an array other than by setting the variable that holds its reference to null.

Constructor
var instanceName = new Array([ val1 [, val2 [, val3 ... ] ] ]);

where the comma-separated values are treated as initial values for array indices 0, 1, 2, and so on. The exception is if a single numeric parameter is supplied, in which case the array’s length property is set to this value.

Properties
constructor Reference to the constructor object, which created the object. (IE4+ (JScript 2.0+), MOZ, N3+ (JavaScript 1.1+), ECMA Edition 1)

length Numeric value indicating the next empty index at the end of the array (not the number of elements in the array). Setting this property to a value less than its current value will undefine any elements with index >= length. (IE4+ (JScript 2.0+), MOZ, N3+ (JavaScript 1.1+), ECMA Edition 1)

prototype Reference to the object’s prototype. (IE4+ (JScript 2.0+), MOZ, N3+ (JavaScript 1.1+), ECMA Edition 1)

Methods
concat([item1 [, item2 [, ...]]]) Appends the comma-separated list of items to the end of the array and returns the new array (it does not operate on the array in place). If any item is an array, its first level is flattened (that is, the item’s elements are appended each as a separate element). (IE4+ (JScript 3.0+), MOZ, N4+ (JavaScript 1.2+), ECMA Edition 1)

join([separator]) Returns the string obtained by concatenating all the array’s elements. If the string separator is supplied, separator will be placed between adjacent elements. The separator defaults to a comma. (IE4+ (JScript 2.0+), MOZ, N3+ (JavaScript 1.1+), ECMA Edition 1)

pop() Removes the last element of the array and returns it. (IE5.5+ (JScript 5.5+), MOZ, N4+ (JavaScript 1.2+), ECMA Edition 3)

push([item1 [, item2 [, ...]]]) Appends the parameters (in order) to the end of the array and returns the new length. (IE5.5+ (JScript 5.5+), MOZ, N4+ (JavaScript 1.2+), ECMA Edition 3)

reverse() Reverses the order of the elements (in place). (IE4+ (JScript 2.0+), MOZ, N3+ (JavaScript 1.1+), ECMA Edition 1)

shift() Removes the first element from the array, returns it, and shifts all other elements down one index. (IE5.5+ (JScript 5.5+), MOZ, N4+ (JavaScript 1.2+), ECMA Edition 3)

slice(begin [, end]) Returns a new array containing the elements from index begin up to but not including index end. If end is omitted, all elements to the end of the array are extracted. If end is negative, it is treated as an offset from the end of the array. (IE4+ (JScript 3.0+), MOZ, N4+ (JavaScript 1.2), ECMA Edition 3)

sort([compareFunc]) Sorts the array in place in lexicographic order. The optional argument compareFunc is a function that can change the behavior of the sort. It will be passed two elements and should return a negative value if the first element is less than the second, a positive value if the second is less than the first, or zero if they are equal. (IE4+ (JScript 2.0+), MOZ, N3+ (JavaScript 1.1+), ECMA Edition 1)

splice(start, howMany [, item1 [, item2 [, ...]]]) Removes howMany elements from the array beginning at index start and replaces the removed elements with the itemN arguments (if passed). An array containing the deleted elements is returned. (IE5.5+ (JScript 5.5+), MOZ, N4+ (JavaScript 1.2+), ECMA Edition 3)

toString() Returns a string containing the comma-separated list of elements. (IE4+ (JScript 2.0+), MOZ, N3+ (JavaScript 1.1+), ECMA Edition 1)

unshift([item1 [, item2 [, ...]]]) Inserts the items (in order) at the front of the array, shifting existing values up to higher indices. (IE5.5+ (JScript 5.5+), MOZ, N4+ (JavaScript 1.2+), ECMA Edition 3)

valueOf() Same as toString(). (IE4+ (JScript 2.0+), MOZ, N3+ (JavaScript 1.1+), ECMA Edition 1)

Support
Supported in IE4+ (JScript 2.0+), Mozilla, N3+ (JavaScript 1.1+), ECMAScript Edition 1.

Notes
In Netscape 4.0–4.05 (JavaScript 1.2) a single numeric parameter to the constructor is added to the single array element—it is not treated as an initial value for length.


Por hoje é tudo, no próximo artigo eu irei falar sobre o objeto String. E plz, comentem, seu comentário é muito importante ;)

segunda-feira, setembro 11, 2006

Estruturas de Controle e Objetos

Como dito no artigo anterior, hoje iremos ver as estruturas de controle do JavaScript e vamos iniciar os estudos a programação orientada a objetos em JavaScript. Como eu disse antes, não tenho interção de ensinar lógica aqui, por isso irei apenas deixar alguns exemplos comentados usando as estruturas de controle, mandem e-mail ou comentários em caso de dúvidas.

Estrutura if e estrura else:

var a = 3;
var b = 5;
var c = 3;

if(a < b) { //se a for menor que b
alert('"a" é menor que "b"');
} else { //caso contrario
alert('"a" não é menor que "b"');
}

if(a == c) { //se a for igual a c
alert('"a" é igual a "c"');
}


Estrutura switch case:

var a = 3;

switch(a) {
case 1: //se a for 1
alert('"a" é 1');
break;
case 2: //se a for 2
alert('"a" é 2');
break;
case 3: //se a for 3
alert('"a" é 3');
break;
case 4: //se a for 4
alert('"a" é 4');
break;
default: //se a nao for nenhum dos casos, entao use o padrao
alert('"a" não está em nenhum dos outros valores');
}


Lembrando que o switch case do JavaScript também aceita valores de string, exemplo:

var a = 'pessoa';

switch(a) {
case 'pessoa':
alert('anda sobre 2 pernas');
break;
case 'cachorro':
alert('anda sobre 4 pernas');
break;
case 'passaro':
alert('voa');
break;
default:
alert('desconhecido');
}


Estrutura while:

var a = 1;

while(a < 10) {
alert(a + ' vezes');
a++;
}


Estrutura for:

for(var i = 0; i < 10; i++) {
alert('ciclo ' + i);
}


Ainda existe outra estrutura para o for, que é o chamado for in, vamos ver isso ainda nesse artigo mais adiante.

Temos a estrutura with mas também deixaremos ela mais para frente.

Objetos
Vamos agora iniciar nossos estudos quanto a criação de objetos com JavaScript. Como dito antes, tudo em JavaScript são objetos, você as vezes cria objetos e os usa sem nem se dar conta disso, vamos ver 2 maneiras de iniciar um objeto em branco:

var meuObjeto = new Object();
var outroObject = {};


Use qual você preferir, eu prefiro a segunda porque assim eu escrevo menos :P
Agora temos incríveis objetos em branco que não fazem nada!! Não é maravilhoso?
Brincadeiras de lado, em JavaScript todos os objetos são dinâmicos, ou seja, eu posso adicionar recursos a eles a qualquer hora, criar variáveis e métodos que nunca existiram nele, podemos mudar isso apenas no objeto atual, ou podemos modificar o seu prototype, modificando o prototype nós podemos adicionar variáveis e métodos para todas as instâncias de um objeto. Vamos então criar nosso primeiro objeto útil:

var Circunferencia = function() {};
Circunferencia.prototype.raio = 1; //valor padrao

Circunferencia.prototype.diametro = function() {
return this.raio * 2;
};

Circunferencia.prototype.perimetro = function() {
return 2 * Math.PI * this.raio;
};

Circunferencia.prototype.area = function() {
return Math.PI * this.raio * this.raio;
};

var b = new Circunferencia();

b.raio = 5;
alert(b.diametro());
alert(b.perimetro());
alert(b.area());

b.raio = 7;
alert(b.diametro());
alert(b.perimetro());
alert(b.area());

b.raio = 10;
alert(b.diametro());
alert(b.perimetro());
alert(b.area());


O objeto para ter seu prototype modificado precisa iniciar-se a partir de uma função, os objetos que sao iniciados das outras formas servem mais como estruturas de dados, para transferir informações.

Temos acima um simples objeto Circunferencia que tem a variável raio e os métodos diametro(), perimetro() e area. Nós estamos adicionando esses métodos no objeto prototype dentro da nossa classe, isso porque quando mudamos o prototype, nós alteramos a classe propriamente dita, então todas as instâncias de bola terão esses métodos/variáveis. Veja que quando estamos dentro de um método e queremos acessar outros recursos da classe, temos que colocar o this seguido de um . para termos a referencia dessas variáveis/métodos. Alguns agora podem estar se perguntando: "e como eu faço pra criar um inicializador para minha classe?". Ai é só colocar-mos algo na função de criação, assim ela se torna o inicializador, vamos ver isso:

var Circunferencia = function(raio) {
this.raio = raio;
};

Circunferencia.prototype.diametro = function() {
return this.raio * 2;
};

Circunferencia.prototype.perimetro = function() {
return 2 * Math.PI * this.raio;
};

Circunferencia.prototype.area = function() {
return Math.PI * this.raio * this.raio;
};

var b = new Circunferencia(5);

alert(b.diametro());
alert(b.perimetro());
alert(b.area());

b.raio = 7;
alert(b.diametro());
alert(b.perimetro());
alert(b.area());

b.raio = 10;
alert(b.diametro());
alert(b.perimetro());
alert(b.area());


Simples não? Na verdade não estamos criando exatamente um objeto novo, e sim modificando um objeto do tipo function, parece meio louco, mas logo logo você se acostuma.

Antes de terminarmos vamos usar nosso exemplo anterior para demostrar o uso de for in e with:

var Circunferencia = function(raio) {
this.raio = raio;
};

Circunferencia.prototype.diametro = function() {
return this.raio * 2;
};

Circunferencia.prototype.perimetro = function() {
return 2 * Math.PI * this.raio;
};

Circunferencia.prototype.area = function() {
return Math.PI * this.raio * this.raio;
};

var b = new Circunferencia(5);

with(b) {
alert(diametro());
alert(perimetro());
alert(area());

raio = 7;
alert(diametro());
alert(perimetro());
alert(area());

raio = 10;
alert(diametro());
alert(perimetro());
alert(area());
}

for(var p in b) {
alert(p + ' ==> ' + b[p]);
}


Como vimos acima, o with é usado para manter um objeto quando ele vai ser muito usado, assim sempre que apontar-mos as coisas, é como se já estivemos avisando que estão na variável que definimos no with. Já o for in serve para passarmos por tudo que tem dentro de um objeto, dizemos o nome da chave (p no nosso caso) in e o nome da variável, assim como se fosse um array associativo, podemos pegar os métodos/variáveis de um objeto passando seu nome dentro de cochetes.

Segue agora a referêcia do Object, todos os objetos do JavaScript contém os métodos e propriedades citadas abaixo:

Object (Built-in Object)
Object is the basic object from which all other objects are derived. It defines methods common to all objects that are often overridden to provide functionality specific to each object type. For example, the Array object provides a toString() method that functions as one would expect an array’s toString() method to behave.This object also permits the creation of user-defined objects and instances are quite often used as associative arrays.

Constructor
var instanceName = new Object();

This statement creates a new (generic) object.

Properties
prototype The prototype for the object. This object defines the properties and methods common to all objects of this type. (IE4+ (JScript 3.0+), MOZ, N3+ (JavaScript 1.1+), ECMA Edition 1)

Methods
hasOwnProperty(property) Returns a Boolean indicating whether the object has an instance property by the name given in the string property. (IE5.5+, MOZ/N6+, ECMA Edition 3)

isPrototypeOf(obj) Returns a Boolean indicating if the object referenced by obj is in the object’s prototype chain. (IE5.5+, MOZ/N6+, ECMA Edition 3)

propertyIsEnumerable(property) Returns a Boolean indicating if the property with the name given in the string property will be enumerated in a for/in loop. (IE5.5+, MOZ/N6+, ECMA Edition 3)

toSource() Returns a string containing a JavaScript literal that describes the object. (MOZ, N4.06+ (JavaScript 1.3+))

toString() Returns the object a string, by default "[object Object]". Very often overridden to provide specific functionality. (IE4+ (JScript 3.0+), MOZ, N2+ (JavaScript 1.0+), ECMA Edition 1)

unwatch(property) Disables watching of the object’s property given by the string property. (N4 (JavaScript 1.2))

valueOf() Returns the primitive value associated with the object, by default the string "[object Object]". Often overridden to provide specific functionality. (IE4+ (JScript 3.0+), N3+ (JavaScript 1.1+), ECMA Edition 1)

watch(property, handler) Sets a watch on the object’s property given in string property. Whenever the value of the property changes, the function handler is invoked with three arguments: the name of the property, the old value, and the new value it is being set to. The handler can override the setting of the new value by returning a value, which is set in its place. (N4 (JavaScript 1.2))

Support
Supported in IE4+ (JScript 3.0+), MOZ, N2+ (JavaScript 1.0+), ECMAScript Edition 1.


Por hoje é tudo, como já sabem: dúvidas, críticas, sugestões, podem me mandar um e-mail (wilkerlucio@gmail.com) ou deixem um comentário ;)

Funções com mais detalhes

Vamos hoje dar continuidade aos nossos estudos, hoje eu vou falar mais sobre escopo, vou falar sobre oque são objetos em JavaScript (calma, criação e implementação de objetos vai ficar pra outro dia, hoje vamos só entender o conceito do que é um objeto em JavaScript) e também vamos aprofundar o estudo de funções.

Antes de continuarmos eu gostaria de dizer que eu não estou tentando ensinar lógica de programação, esses artigos são voltados a pessoas que já sabem lógica de programação, oque eu pretendo passar aqui é como usar a linguagem JavaScript.

Escopo e Objetos, a relação existente
No artigo passado nós vimos um pouco sobre o escopo das variáveis, vimos a diferença entre uma variável global e uma variável criada internamente para uma função, agora vamos entender melhor oque realmente acontece.

Em JavaScript, praticamente tudo (apenas com a excessão de tipos primitivos) são objetos, isso mesmo, uma string é um objeto, um array(falaremos sobre arrays em outros artigos) é um objeto, até mesmo uma função é um objeto no JavaScript.

Os escopos sempre são relativos aos objetos, para uma variável existir, ela tem que estar dentro de um objeto, e esse objeto é o seu escopo, como eu disse antes, o escopo global é o objeto window, quando você declara uma var dentro de uma função, você está criando uma variável no escopo daquela função, mais a frente ainda nesse artigo eu mostrarei outras formas de criar funções, e vocês verão que uma função pode ser tratada da mesma forma que uma variável.

Com isso eu termino minha explicação sobre escopo, mas a melhor forma de realmente entender isso é fazendo na prática, eu recomendo que vocês façam testes pra ver oque acontece com uma variável em diferentes escopos, porque essa é a melhor forma de enteder isso.

Funções, conhecendo-as melhor
Nós ja aprendemos a criar funções, a passar parâmetros para a mesma e também como retornar dados, hoje vamos explorar melhor o conceito de funções em JavaScript e também vamos aprender a usar mais recurso das funções em JavaScript.

Primeiro eu quero que fique bem claro para todos: "Funções de JavaScript são objetos".
Exatamente, pra quem entender de oop, eu poderia dizer que a propria função do javascript já contem seus métodos e variáveis internas, ela realmente é um objeto e deve ser tratada como tal, vamos ver uma outra forma de criar uma função, usando essa forma fica mais claro o conceito de que ela é um objeto:

var minhaFuncao = function() {
alert('funcao criada com sintaxe de variavel');
};

minhaFuncao();


Como podemos ver, essa sintaxe parece que estamos criando uma variável, mas estamos criando uma função. Optar por usar esse modo ou o outro que vimos anteriormente é uma questão de gosto, mas existe casos que só é possivel criar dessa 2 forma, eu sinceramente prefiro essa sintaxe mostrada acima, pois nela temos uma melhor controle sobre qual escopo a função está sendo criada.

obs: note que quando usamos essa sintaxe, colocamos um ponto e vírgula (;) após a criação dela, essa é a sintaxe correta, pois estamos declarando uma variável, e sempre depois de uma declaração tem que vir um ponto e vírgula.

As vezes nós criamos uma função sobre um escopo, mas precisamos que ela seja executada sobre um escopo diferente, entao como fazer isso? Como mudar o escopo da função?

Em JavaScript isso é facil, como eu disse, funções são objetos, e elas tem seus métodos, uma função pode ser chamada de 3 formas diferentes, vamos ve-las:

var soma = function(a, b) {
var resultado = a + b;
alert('Resultado da soma: ' + resultado);
};

soma(2, 3); //essa é a forma que estamos usando, apenas diz o nome da funcao e acresce de ()
soma.call(this, 2, 3); //esse é outro modo de chamar a função
soma.apply(this, [2, 3]); //e temos também esse terceiro


Vamos agora entender a diferença entre esses 3 modos:

soma(2, 3) => esse é o método padrão, a função será executada no escopo de onde ela foi chamada, e os argumentos são passados normalmente.

soma.call(this, 2, 3) => esse é muito parecido com o padrão, dizemos o nome da função e chamados o método call da mesma, a única diferença se dá no primeiro argumento, o primeiro argumento não será passado, ao invéz disso, o primeiro argumento informa em qual escopo a função deve ser executada, usando this mandamos executar no escopo atual, e nesse caso não existe diferença entre esse modo e o padrão.

soma.apply(this, [2, 3]) => esse quase igual ao anterior, o primeiro argumento funciona da mesma forma (para expecificar o escopo) mas temos diferenca na hora de passar os argumentos para a função. No lugar de passar os argumentos separados por vírgula, oque passamos é um array contendo todos os argumentos, essa forma é mais dinâmica que as outras.

obs: quando usamos [] estamos nos referindo a arrays, vamos entender isso melhor em futuros artigos.

Vamos agora aprender a usar parâmetros não definidos nas funções.
Imagine que você queria uma função que some todos os parâmetros que forem passados para a mesma, mas você não sabe quantos parâmetros serão passados para essa função, para resolver esse problema, usaremos uma variável que é definida internamente pelo objeto da função, a variável arguments.

A variável arguments é definida automaticamente em qualquer função, ela é um array que contém todos os parâmetros passados para a função, vamos criar nossa função que soma todos os argumentos passados, assim veremos seu uso:

var somaTudo = function() {
var total = 0; //iniciando a variavel que vai guardar o valor das somas

for(var i = 0; i < arguments.length; i++) {
total += arguments[i]; //adicionando valor na variavel total
}

return total;
};

alert(somaTudo(3, 2, 4, 8));
alert(somaTudo(4, 5, 1, 3, 9, 6, 13));
alert(somaTudo());
alert(somaTudo(10));
alert(somaTudo(3, 2, 1, 5, 6, 7));


Viram como é simples o uso da variável arguments?

Para finalizar, vou deixar aqui uma referência (em inglês) do objeto Function, assim vocês podem ir testando seus métodos e variáveis, e lembrem-se sempre, a melhor maneira de aprender é fazendo, façam testes por ai, eu não tive tempo pra passar exercícios, mas futuramente eu estarei passando exercícios para vocês tentarem resolver, segue a referência:

Function (Built-in Object)
Function is the object from which JavaScript functions are derived. Functions are first-class data types in JavaScript, so they may be assigned to variables and passed to functions as you would any other piece of data. Functions are, of course, reference types.

The Function object provides both static properties like length and properties that convey useful information during the execution of the function, for example, the arguments[] array.

Constructor
var instanceName = new Function([arg1 [, arg2 [, ...]] ,] body);

The body parameter is a string containing the text that makes up the body of the function. The optional argN’s are the names of the formal parameters the function accepts. For example:

var myAdd = new Function("x", "y", "return x + y");
var sum = myAdd(17, 34);

Properties
arguments[] An implicitly filled and implicitly available (directly usable as "arguments" from within the function) array of parameters that were passed to the function. This value is null if the function is not currently executing. (IE4+ (JScript 2.0+), MOZ, N3+ (JavaScript 1.1+), ECMA Edition 1)

arguments.callee Reference to the current function. This property is deprecated. (N4+, MOZ, IE5.5+)

arguments.caller Reference to the function that invoked the current function. This property is deprecated. (N3, IE4+)

arguments.length The number of arguments that were passed to the function. (IE4+ (JScript 2.0+), MOZ, N3+ (JavaScript 1.1+), ECMA Edition 1)

arity Numeric value indicating how many arguments the function expects. This property is deprecated. (N4+, MOZ)

caller Reference to the function that invoked the current function or null if called from the global context. (IE4+ (JScript 2.0+), MOZ, N3+)

constructor Reference to the constructor object that created the object. (IE4+ (JScript 2.0+), N3+ (JavaScript 1.1+), ECMA Edition 1)

length The number of arguments the function expects to be passed. (IE4+ (JScript 2.0+), N3+ (JavaScript 1.1+), ECMA Edition 1)

prototype Reference to the object’s prototype. (IE4+ (JScript 2.0+), N3+ (JavaScript 1.1+), ECMA Edition 1)

Methods
apply(thisArg [, argArray]) Invokes the function with the object referenced by thisArg as its context (so references to this in the function reference thisArg). The optional parameter argArray contains the list of parameters to pass to the function as it is invoked. (IE5.5+ (JScript 5.5+), N4.06+ (JavaScript 1.3+), MOZ, ECMA Edition 3)

call(thisArg [, arg1 [, arg2 [, ...]]]) Invokes the function with the object referenced by thisArg as its context (so references to this in the function reference thisArg). The optional parameters argN are passed to the function as it is invoked. (IE5.5+ (JScript 5.5+), N4.06+ (JavaScript 1.3+), MOZ, ECMA Edition 3)

toString() Returns the string version of the function source. The body of built-in and browser objects will typically be represented by the value "[native code]". (IE4+ (JScript 2.0+), N3+ (JavaScript 1.1+), MOZ, ECMA Edition 1)

valueOf() Returns the string version of the function source. The body of built-in and browser objects will typically be represented by the value "[native code]". (IE4+ (JScript 2.0+), N3+ (JavaScript 1.1+), MOZ, ECMA Edition 1)

Support
Supported in IE4+ (JScript 2.0+), N3+ (JavaScript 1.1+), MOZ, ECMAScript Edition 1.


Por hoje é tudo, no próximo artigos falaremos sobre estruturas de controle e objetos, com isso iremos finalizar o "core" do JavaScript, e depois começaremos a falar dos objetos Built-In (Array, Date, String...).

Grato a atenção de todos.

Conceitos, Variáveis e Funções

Olá, bem vindo a esse blog. Esse é meu primeiro post nesse blog, comecarei dando noções básicas de Javascript. O objetivo desse blog eh passar informações desde o básico até o avançado sobre Javascript, o Javascript está sendo muito difundido na web e muitas pessoas não estão conseguindo acompanhar esse progresso devido a não ter a base do Javascript. Como eu disse antes, eu vou comecar as coisas do básico, mesmo que você ja saiba Javascript eu recomendaria que você desse uma lida nesses posts, porque as vezes umas coisas bestas passam despercebidas, mas essas besteiras podem fazer uma grande diferenca quando chega a hora da aplicação final.

Um pouco de história
O Javascript foi criado pela Netspace em 1995 e era chamado inicialmente de LiveScript, depois ele passou a ter o nome JavaScript. No Internet Explorer, o nome da linguagem é JScript, eles a chamam assim para dizer que não é a mesma coisa, e realmente não é, e devido a isso é que temos os problemas de incompatibilidade entre o script nos browsers, o JScript tem muitos recursos que não existem no JavaScript, mas como no mundo atual em 98% dos casos (isso tira apenas os casos onde fazemos um sistema apenas interno, onde temos certeza que só vão usar aquele browser, e mesmo assim não é recomendavel) nós temos que fazer scripts que rodem em qualquer browser.

Inicialmente o JavaScript era visto como uma "gambiarra" da web, que estava completamente fora de padrões. Essa visão tem mudado recentemente devido a difusão do AJAX (Asyncronous Javascript And XML), e não foi o JavaScript que mudou, e sim os programadores que comecaram a fazer seu uso de forma correta.

Chega de blablabla
Se você teve paciência para ler até aqui ótimo (mas nem vem, eu sei que teve gente que pulo os textos anteriores, mas tudo bem XD).

Vamos comecar entendendo o conceito de funções e variáveis em Javascript. A declaração de variáveis em JavaScript é algo muito simples, para os testes iniciais usaremos o seguinte padrão:

<html>
<head>
<title> JavaScript Dev </title>
</head>
<body>
<script type="text/javascript">
</script>
</body>
</html>


Como podem ver temos um HTML simples, para escrever JavaScript nós usamos a tag <script type="text/javascript"></script>, nossos scripts vão ficar dentro dessas tags. obs: os códigos a seguir devem ficar entre as tags <script>.

var a = 5;
var b = 10;
var c = a + b;

alert(c);


Isso foi uma simples declaração de variáveis, declaramos a variável a com o valor 5, depois declaramos a variável b com o valor 10 e finalmente a variável c que tem o valor da soma de a com b, então usamos a função alert() que abre uma caixa de texto com um valor (que no nosso caso vai exibir o valor da variável c).

Em JavaScript as variáveis não são tipadas, ou seja, a mesma variável pode ter um valor numérico, ou string, ou objeto ou qualquer tipo desejado, isso tem uma perda de desempenho, mas para casos de linguagens isso é mais benefício do que perda.

Vamos ver agora a declaração de funções:
function testeFuncao() {
alert('a função foi executada');
}

testeFuncao();


Declaramos a função testeFuncao() que simplesmente exibe uma caixa com uma mensagem, as funções podem retornar (ou não) um valor, nesse nosso primeiro exemplo ela não retorna nada, ela apenas executa (seria o caso de funções void em linguagens como C ou Java). Agora vamos ver uma função que retorna um valor:

function soma(a, b) {
return a + b;
}

var n1 = 5;
var n2 = 3;
var valor = soma(n1, n2);

alert(valor);


Agora temos algo um pouco mais complicado, como podem ver, dessa vez a função recebe 2 parâmetros, quando declaramos parâmetros para as funções, temos seus nomes, e eles devem ser passados na mesma ordem que foram declarados (ou seja, nosso n1 vai virar b e n2 vai virar b), oque a função faz é pegar esses 2 parâmetros e soma-los, retornando esse resultado. Logo após a declaração nós criamos as variaveis n1 e n2, depois mandamos a variável valor guardar o resultado da soma das duas (usando a nossa função somar), e finalmente mandamos exibir esse resultado.

Escopo de variáveis
Por ultimo vamos entender um pouco sobre escopo de variáveis. O escopo de uma variável serve para saber onde está aquela variável, pois podemos ter varias variáveis com o mesmo nome em escopos diferentes. Vamos entender melhor isso atravéz de um exemplo:

var minhaVariavel = 10;

function mostraGlobal() {
alert(minhaVariavel);
}

function mostraLocal() {
var minhaVariavel = 5;
alert(minhaVariavel);
}

function mexeGlobal() {

minhaVariavel += 3;
alert(minhaVariavel);
}

function mexeLocal() {

var minhaVariavel = 2;
minhaVariavel += 5;
alert(minhaVariavel);
}

mostraGlobal();
mostraLocal();
mostraGlobal();
mexeGlobal();
mexeLocal();
mexeGlobal();
mexeLocal();
mexeGlobal();
mexeLocal();


Temos agora várias funções, primeiro declaramos a variável global chamada minhaVariavel, vemos nas funções a parte interessante, se você chamar uma variável que não foi declarada dentro da função, ele vai buscar essa variável no escopo global (na verdade, o escopo global do javascript é o objeto window, ou seja, chamar uma variavel dessa forma seria a mesma coisa que escrever window.minhaVariavel, mas você não precisa entender isso agora, nos próximos artigos isso será melhor explicado), e caso não encontre no escopo global ele vai retonar uma valor undefined. Já se dentro da função nós declaramos var minhaVariavel ele vai criar uma nova variável com esse nome no escopo da função, com isso ele sempre vai mexer na variável local, e vai deixar a global de lado. Podem ver o seguinte, no script nós executamos primeiro a função que exibe a variável global, depois chamamos a função que mostra a local, como podem ver, na que mostra a variável local nos fazemos uma atribuição à variável, e depois mostramos a global novamente, para provar que ela não foi alterada. Nos outros testes nós mexemos algumas vezes na variável em diferentes escopos, e como podem ver a variável global sempre vai mudando, enquanto a local sempre é uma nova variável.

Por hoje isso é tudo. Tentei nesse artigo ensinar o básico sobre variáveis e funções, a parte de escopo pode ter ficado um pouco difícil de entender para algumas pessoas, mas não se preocupe, nos futuros artigos iremos entender melhor como funciona o escopo e ficará mais facil.

Quem já entende de JavaScript pode ter achado isso muito chato, mas futuramente entraremos em assuntos bem mais complexos do JavaScript, então aguardem os futuros artigos.

Em caso de dúvidas me mandem um e-mail no seguinte endereço: wilkerlucio@globo.com.

Grato a atenção de quem leu meu artigo, o segundo artigo vai aprofundar o estudo de funções.