let arr =newArray();let arr = [];// most time use [...]let fruits = ["Apple","Orange","Plum"];alert( fruits[0] ); // Applealert( fruits[1] ); // Orangealert( fruits[2] ); // Plum// replacefruits[2] ='Pear'; // now ["Apple", "Orange", "Pear"]// add new onefruits[3] ='Lemon'; // now ["Apple", "Orange", "Pear", "Lemon"]// lengthlet fruits = ["Apple","Orange","Plum"];alert( fruits.length ); // 3// store any type data// mix of valueslet arr = [ 'Apple', { name:'John' },true,function() { alert('hello'); } ];// get the object at index 1 and then show its namealert( arr[1].name ); // John// get the function at index 3 and run itarr[3](); // hello
Methods pop/push, shift/unshift
.pop() 從 array 最後拿走一個值。
let fruits = ["Apple","Orange","Pear"];alert( fruits.pop() ); // remove "Pear" and alert italert( fruits ); // Apple, Orange
let fruits = []; // make an arrayfruits[99999] =5; // assign a property with the index far greater than its lengthfruits.age =25; // create a property with an arbitrary name
Performance
fruits.shift(); // take 1 element from the start
fruits.pop(); // take 1 element from the end
Loops
let arr = ["Apple","Orange","Pear"];for (let i =0; i <arr.length; i++) {alert( arr[i] );}// same// iterates over array elementsfor (let fruit of fruits) {alert( fruit );}// same// 可以使用 for..in 但會造成一些問題;有些類似 array 的物件,有其他屬性也會被帶入迴圈;用這個方法效能比較差for (let key in arr) {alert( arr[key] ); // Apple, Orange, Pear}
A word about “length”
array 的 length 屬性準確地說是 index 值 +1,所以當 index 很大 length 也很大。
let fruits = [];fruits[123] ="Apple";alert( fruits.length ); // 124
let arr = [1,2,3,4,5];arr.length=2; // truncate to 2 elementsalert( arr ); // [1, 2]arr.length=5; // return length backalert( arr[3] ); // undefined: the values do not return
new Array()
let arr =newArray("Apple","Pear","etc");// 用 new 創造 array 可能會造成 array 存在但裡面沒有值。let arr =newArray(2); // will it create an array of [2] ?alert( arr[0] ); // undefined! no elements.alert( arr.length ); // length 2
Multidimensional arrays
let matrix = [ [1,2,3], [4,5,6], [7,8,9]];alert( matrix[1][1] ); // the central element