陣列(Array)是 JavaScript 中用來儲存一組有序資料的集合。
陣列可以包含各種資料型別的值,例如數字、字串、布林值,甚至其他陣列或物件。
[]
let fruits = ["蘋果", "香蕉", "橘子"];
Array
建構函式let numbers = new Array(1, 2, 3);
0
開始計數。例如: 第一個元素的索引是 0
,第二個是 1
,依此類推。length
:可以取得陣列的長度。let items = [1, 2, 3, 4];
console.log(items.length); // 輸出:4
let colors = ["紅", "藍", "綠"];
console.log(colors[0]); // 輸出:"紅"
let colors = ["紅", "藍", "綠"];
colors[1] = "黃色"; // 將 "藍" 修改為 "黃色"
console.log(colors); // 輸出:["紅", "黃色", "綠"]
let arr = ['a', 'b', 'c'];
const count = arr.push('d');
console.log(count); // 返回:4
console.log(arr); // ["a", "b", "c", "d"]
let arr = ['a', 'b', 'c'];
console.log(arr.pop()); // 輸出:"c"
console.log(arr); // 輸出:["a", "b"]
let arr = ['a', 'b', 'c'];
const firstElement = arr.shift();
console.log(firstElement); // 輸出:"a"
console.log(arr); // 輸出:["b", "c"]
let arr = ['a', 'b', 'c'];
console.log(arr.unshift('d', 'f')); // 返回:5
console.log(arr); // 輸出:["d", "f", "a", "b", "c"]
let numbers = [1, 2, 3];
numbers.forEach(num => console.log(num));
// 輸出:1
// 輸出:2
// 輸出:3
let numbers = [1, 2, 3];
let doubled = numbers.map(num => num * 2);
console.log(numbers) // [1,2,3]
console.log(doubled) // [2, 4, 6]
let numbers = [1, 2, 3];
let evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(numbers) // [1,2,3]
console.log(evenNumbers) // [2]
let arr1 = [1, 2];
let arr2 = [3, 4];
let combined = arr1.concat(arr2);
console.log(combined) // [1, 2, 3, 4]
const pets = ['cat', 'dog', 'bat'];
console.log(pets.includes("cat")); // 輸出:true