comments | Javascript source | Execution result in your current browser |
|
document.write("Initialize an array");
var array1=new Array();
array1[0]="One";
array1[1]=2;
array1[2]=new Date();
document.write("<p> array1 is: "+array1);
|
|
| //change array element
array1[0]=1;
|
|
| //access an array member
document.write("the first item: "+array1[0]);
|
|
| //property: length
document.write("array length: "+array1.length);
|
|
| //loop method 1: c-like array loop
for(var i=0; i<array1.length; i++) {
var val=array1[i];
document.write(i+" => "+val+"<br/>");
}
|
|
| //loop method 2: for ... in: loop through index of array
for (var i in array1) {
var val=array1[i];
document.write(i+" => "+val+"<br/>");
}
|
|
| //loop method3: for each ... in: loop through values of array
for each (var val in array1) {
document.write(val+"<br/>");
}
|
|
| //unshift: add element at the begining
array1.unshift("First");
for (var i in array1) {
document.write(array1[i]+"<br/>");
}
|
|
| //push: add element at last
array1.push("Last");
for (var i in array1) {
document.write(array1[i]+"<br/>");
}
|
|
| //pop: remove the last element
document.write("removed the last element: "+array1.pop()+"<br/>");
for (var i in array1) {
document.write(array1[i]+"<br/>");
}
|
|
| //shift: remove the first element
document.write("removed first element: "+array1.shift()+"<br/>");
for (var i in array1) {
document.write(array1[i]+"<br/>");
}
|
|