數組操作
刪除元素
const arr = [1, 2, 3, 4, 5];
// 1. shift() - 刪除首項,返回被刪值
arr.shift(); // 返回 1,arr 變 [2,3,4,5]
// 2. pop() - 刪除尾項,返回被刪值
arr.pop(); // 返回 5,arr 變 [1,2,3,4]
// 3. splice(index, count) - 任意位置刪除,返回被刪陣列
arr.splice(2, 1); // 從索引 2 刪 1 項,返回 [3],arr 變 [1,2,4,5]
arr.splice(1, 2); // 從索引 1 刪 2 項,返回 [2,4],arr 變 [1,5]
// 4. filter() - 不變原陣列,返回新陣列(推薦函數式風格)
const filtered = arr.filter(x => x !== 2); // [1,3,4,5]
添加元素
const arr = [1, 2, 3];
// 1. push() - 尾部添加,返回新長度
arr.push(4, 5); // [1,2,3,4,5]
// 2. unshift() - 頭部添加
arr.unshift(0); // [0,1,2,3,4,5]
// 3. splice(index, 0, ...items) - 指定位置插入
arr.splice(2, 0, 'a', 'b'); // [0,1,'a','b',2,3,4,5]
// 4. concat() - 合併陣列,不變原陣列
const newArr = arr.concat([6,7]); // [0,1,'a','b',2,3,4,5,6,7]
// 5. ES6 展開運算符
const merged = [...arr, 8, 9]; // [0,1,'a','b',2,3,4,5,6,7,8,9]
修改/替換元素
const arr = [1, 2, 3, 4, 5];
arr[2] = 30; // 直接索引賦值
arr.splice(2, 1, 30); // splice 替換:刪 1 項並插入 30
// 批量替換
arr.splice(1, 3, 'x', 'y', 'z'); // [1, 'x', 'y', 'z', 5]
查找與遍歷
const arr = [5, 12, 8, 130, 44];
arr.indexOf(8); // 2 (找不到返回 -1)
arr.lastIndexOf(8); // 2
arr.find(x => x > 10); // 12 (找到第一個符合條件的值)
arr.findIndex(x => x > 10); // 1 (索引)
arr.includes(12); // true
arr.filter(x => x > 10); // [12, 130, 44]
arr.map(x => x * 2); // [10, 24, 16, 260, 88]
arr.forEach((v, i) => console.log(i, v));
JSON 對象(純物件)操作
const obj = { name: 'Alice', age: 25 };
// 添加/修改屬性
obj.email = 'alice@example.com'; // 新增
obj['phone'] = '123-456'; // 方括號語法(鍵含特殊字符或變量)
obj.age = 26; // 修改
// 刪除屬性
delete obj.phone; // true,屬性移除
// Reflect.deleteProperty(obj, 'age'); // 現代 API
// 判斷屬性存在
'name' in obj; // true
obj.hasOwnProperty('name'); // true (不含原型鏈)
Object.hasOwn(obj, 'name'); // ES2022 推薦
// 遍歷
Object.keys(obj).forEach(k => console.log(k, obj[k]));
for (const [k, v] of Object.entries(obj)) { ... }
// 合併物件 (淺合併)
const merged = { ...obj, city: 'Beijing', age: 27 }; // { name, age:27, email, city }
// Object.assign({}, obj, { city: 'Beijing' }); // 等價
深度操作工具函數
// 深度刪除物件屬性 (按路徑)
function deepDelete(obj, path) {
const keys = path.split('.');
let cur = obj;
for (let i = 0; i < keys.length - 1; i++) {
if (!cur || typeof cur !== 'object') return false;
cur = cur[keys[i]];
}
return delete cur[keys[keys.length - 1]];
}
// 深度設置值
function deepSet(obj, path, value) {
const keys = path.split('.');
let cur = obj;
for (let i = 0; i < keys.length - 1; i++) {
if (!cur[keys[i]]) cur[keys[i]] = {};
cur = cur[keys[i]];
}
cur[keys[keys.length - 1]] = value;
return obj;
}
// 使用
const data = { user: { profile: { name: 'Bob' } } };
deepSet(data, 'user.profile.age', 30);
deepDelete(data, 'user.profile.name');
避坑指南
splice 會修改原陣列,filter/map/slice 返回新陣列。
delete obj.prop 僅移除自有屬性,原型鏈屬性不受影響。
- 陣列稀疏洞:
delete arr[2] 會留下 empty 槽位,length 不變,遍歷會跳過。優先用 splice 或 filter。
- JSON 序列化會忽略
undefined、function、Symbol、循環引用。