數組在JavaScript中屬於引用數據類型,這意味着它存儲在堆內存中,而棧內存裏只存了它的引用地址。所以當你把一個數組賦值給另一個變量時,其實是在複製引用,而不是複製整個數組哦!
🧱 數組的創建方式(超實用)
✅ 推薦方式:數組字面量(最簡潔)
// 創建包含不同類型元素的數組
let fruits = ['蘋果', '香蕉', '橙子', 100, true, {name: '小明'}];
⚠️ 用Array構造函數(注意陷阱)
// 創建長度為5的數組(元素為undefined,不是5個元素!)
let arr = new Array(5);
console.log(arr); // [undefined, undefined, undefined, undefined, undefined]
// 正確創建元素數組
let arr2 = new Array('蘋果', '香蕉', '橙子');
🔍 數組的基本操作
📌 訪問元素
let colors = ['red', 'green', 'blue'];
console.log(colors[0]); // 'red'(索引從0開始)
console.log(colors[2]); // 'blue'
console.log(colors[5]); // undefined(超出範圍)
📏 獲取數組長度
console.log(colors.length); // 3
🛠️ 數組的常用方法(重點來了!)
📦 1. 修改原數組的方法("危險分子",用時小心!)
尾部操作(高效!)
let numbers = [1, 2, 3];
numbers.push(4); // [1, 2, 3, 4](添加到末尾)
numbers.pop(); // 4(移除並返回最後一個元素)
頭部操作(效率較低,慎用!)
numbers.unshift(0); // [0, 1, 2, 3](添加到開頭)
numbers.shift(); // 0(移除並返回第一個元素)
萬能"瑞士軍刀" splice()
let arr = [1, 2, 3, 4, 5];
arr.splice(2, 2); // [3, 4](刪除索引2開始的2個元素)
arr.splice(2, 0, 3, 4); // [1, 2, 3, 4, 5](在索引2插入元素)
排序與反轉
let nums = [3, 1, 2];
nums.sort(); // [1, 2, 3](按字符串排序,注意!)
nums.sort((a, b) => a - b); // [1, 2, 3](按數字排序)
nums.reverse(); // [3, 2, 1](反轉數組)
🌈 2. 不修改原數組的方法(安全!)
查找元素
let names = ['Tom', 'Lily', 'Sam', 'Bill'];
console.log(names.indexOf('Lily')); // 1
console.log(names.includes('Tom')); // true
console.log(names.find(name => name.length > 3)); // 'Lily'
創建新數組
// 創建新數組,每個元素乘以2
let doubled = numbers.map(num => num * 2);
// 篩選出大於2的元素
let filtered = numbers.filter(num => num > 2);
// 從數組中獲取最後一個元素(超方便!)
console.log(colors.at(-1)); // 'blue'
💡 一些實用小技巧
- at()方法:可以直接用負數索引,
colors.at(-1)就是獲取最後一個元素,不用計算長度! - with()方法:創建新數組,替換指定位置的元素,不修改原數組
let newColors = colors.with(1, 'purple'); // ['red', 'purple', 'blue']
- copyWithin():在數組內部複製元素,不改變長度
let arr = [1, 2, 3, 4, 5];
arr.copyWithin(0, 3); // [4, 5, 3, 4, 5]
- reduceRight():反向迭代數組,從後往前處理
let str = ['a', 'b', 'c'].reduceRight((acc, curr) => acc + curr);
console.log(str); // 'cba'