Array é criado com 3 elementos
Armazenamento de valores em uma posição do array
var dias = [];
dias[0] = "Segunda";
dias[1] = "Terça";
dias[2] = "Quarta";
Para anexar itens no final
Cuidado com emulação de arrays associativos
var pessoa = [];
pessoa["nome"] = "Bruno";
pessoa["idade"] = 54;
alert(pessoa["nome"]); // Retorna 'Bruno'
alert(pessoa.idade); // Retorna 54
Limites de um array
Arrays em JS crescem indefinidamente
Se um elemento for ignorado, os demais são preenchidos com undefined
var dias = [];
dias[2] = "Quarta";
Para obter o tamanho de um vetor use a propriedade .length
var x = ['a','b','c'];
alert(x.length); // Devolve o valor 3
A propriedade length também pode ser usada para diminuir um vetor
x = [1,2,3,4];
alert(x[3]); // exibe 4
x.length = 3;
alert(x[3]); // exibe undefined
Tipos de itens em um array
Qualquer tipo de dado pode ser armazenado em um array
Array formado pelo mesmo tipo de dado
var f = [function(a,b) {return (a+b);},
function(a,b) {return (a-b);},
function(a,b) {return (a*b);}];
var x = f[0](4,3);
alert(x); // Exibe 7
x = f[1](4,3);
alert(x); // Exibe 1
Array formado por tipos de dados diferentes
Array formado por arrays
var arr=[[1,2],[3,4],[4,5]];
alert(arr.length); // Exibe 3
alert(arr[1]); // Exibe 3,4
alert(arr[1].length); // Exibe 2
alert(arr[2][1]); // Exibe 5
arr = [
[1,2],
[3,4,5],
[5,6,7,8]
];
alert(arr[1][2]); // Exibe 5
Procure escrever as matrizes em mais de uma linha
var arr = [
[1,2],
[3,4,5],
[5,6,7,8]
];
Apagando elementos
Alterar a propriedade length
x = [1,2,3,4];
alert(x[3]); // exibe 4
x.length = 3;
alert(x[3]); // exibe undefined
Remover um elemento de uma posição qualquer usando delete
var x = [5,4,3,2,1];
delete(x[3]);
// Em x temos [5, 4, 3, undefined, 1]
Deixa buracos no array
Remover um elemento usando splice
x = [5,4,3,2,1];
x.splice(3,1);
// Em x temos [5,4,3,1]
Percorrendo os elementos de um vetor
Usando for..in
x = ['a','b','c','d','e'];
for(var i in x) {
alert(i);
alert(x[i]);
}
// Passo 1:
// Exibe 0 e 'a'
// Passo 2:
// Exibe 1 e 'b'
// Passo 3:
// Exibe 2 e 'c'
//...
A ordem não é garantida
Pode devolver propriedades inesperadas
x = ['a','b','c','d','e'];
x.y = 'g';
for(var i in x) {
alert(i);
alert(x[i]);
}
// Passo 1:
// Exibe 0 e 'a'
// Passo 2:
// Exibe 1 e 'b'
// Passo 3:
// Exibe 2 e 'c'
//...
// Passo 6:
// Exibe y e g
x = ['a','b','c','d','e'];
x.y = 'g'; // Ignorado pelo for!
for(var i=0;i<x.length;i++) {
alert(i);
alert(x[i]);
}
x = [1,2,3,4,5,6];
var s = 0;
for(var i=0;i<x.length;i++) {
s = s + x[i];
}
alert(s); // Devolve 21
f = [function (a,b) {return a+b;}, function (a,b) {return a-b;},function (a,b) {return a*b;},function (a,b) {return a/b;}];
for(var i=0;i<f.length;i++) {
alert( f[i](5,4) );
}
// Devolve: 9, 1, 20, 1.25
Ampliando as funcionalidades do tipo Array
JavaScript permite que os tipos básicos sejam aumentados
Aumentando o tipo Array, todos os arrays criados herdam propriedades do protótipo
Array.prototype.metodo = function () {
}
Array.prototype.eliminaPrimeiro = function () {
this.splice(0,1);
}
x = [1,2,3,4,5];
alert(x[0]); // Exibe o 1
x.eliminaPrimeiro();
alert(x[0]); // Exibe o 2
Array.prototype.mult = function (m) {
for(var i=0;i<this.length;i++) {
this[i] = this[i]*m;
}
}
x = [1,2,3,4,5];
x.mult(10); // Agora em x temos [10,20,30,40,50]
Array.prototype.somaTodos = function () {
var s = 0;
for(var i=0;i<this.length;i++) {
s = s + this[i];
}
return s;
}
x = [1,2,3,4,5];
alert(x.somaTodos()); // Devolve 15
y = [10,20,30];
alert(y.somaTodos()); // Devolve 60
Principais operações com arrays
Concatenar dois arrays
x = [1,2,3,4,5];
y = [6,7,8];
z = x.concat(y);
alert(x); // Exibe 1,2,3,4,5
alert(y); // Exibe 6,7,8
alert(z); // Exibe 1,2,3,4,5,6,7,8
Juntar todos os elementos de um array em um string
x = ['Jamanta','da','Silva'];
s = x.join(' ');
s2 = x.join('-');
alert(s); // Exibe Jamanta da Silva
alert(s2); // Exibe Jamanta-da-Silva
Colocar um elemento no fim do array
x= [1,2,3,4,5];
x.push(6);
alert(x); // Exibe 1,2,3,4,5,6
Remover elementos
Remover um elemento do fim do array
x= [1,2,3,4,5];
alert(x.pop()); // Exibe 5
alert(x.pop()); // Exibe 4
alert(x.pop()); // Exibe 3
alert(x.pop()); // Exibe 2
alert(x.pop()); // Exibe 1
alert(x.length); // Array está com 0 elementos agora
Remover um elemento do início do array
x = [1,2,3,4,5];
alert(x.shift(0)); // Exibe 1
alert(x[0]); // Exibe 2
Remover elementos de qualquer posição do array
x = [5,4,3,2,1];
x.splice(3,1);
// Em x temos [5,4,3,1]
x = [5,4,3,2,1,0,1,2,3];
x.splice(0,5);
// Em x temos [0,1,2,3]
Retornar um vetor de dentro de outro
x = [5,4,3,2,1,0,1,2,3];
y = x.slice(5); // y é [0,1,2,3]
Inverter os elementos de um array
x= [1,2,3,4,5];
x.reverse();
alert(x); // Exibe [5,4,3,2,1]
Ordenar os elementos de um vetor
x = [3, 4, 1, 2, 6, 7, 5];
y = x.sort();
y // em y temos [1, 2, 3, 4, 5, 6, 7]