0
,第二個是 1
,以此類推;最後一個元素在 array.length - 1
。使用中括號 []
建立陣列,元素之間用逗號區隔。
var array = ["第一個內容", "第二個內容"];
console.log(array[0]); //"第一個內容"
console.log(array[1]); //"第二個內容"
計算陣列長度:
console.log(array.length); //2
存取最後一個元素:
console.log(array[array.length - 1]);
範例:
var score = [1, 3, 5];
score.push(10);
console.log(score); //[1, 3, 5, 10]
score.pop();
console.log(score); //[1, 3, 5]
有時候我們需要把元素轉換成不同型別:
5 + ""
→ "5"
+"5"
→ 5
!!5
→ true
如果陣列裡的元素仍然是陣列,就稱為「巢狀陣列」。
var arr = [[1, 2], [3, 4]];
console.log(arr[0][1]); //2
迭代指的是「逐一處理陣列中的元素」,常見方法有:
forEach()
對陣列中的每個元素執行指定函式,但不會回傳新陣列(回傳值是 undefined
)。
語法:
array.forEach((element, index, array) => {
// 對每個元素執行的動作
});
範例:
const array1 = ["a", "b", "c"];
array1.forEach((element) => console.log(element));
// 輸出: a
// 輸出: b
// 輸出: c