如何用解构和扩展运算符高效处理复杂数组和对象?

摘要:一、数组应用示例 这些示例展示了 ES6 解构赋值和扩展运算符的强大功能,它们让代码更加简洁、可读性更强 1.基本解构+扩展 const arr = [1, 2, 3, 4, 5];获取前两个元素,剩余元素放入新数
一、数组应用示例 这些示例展示了 ES6 解构赋值和扩展运算符的强大功能,它们让代码更加简洁、可读性更强 1.基本解构+扩展 const arr = [1, 2, 3, 4, 5]; // 获取前两个元素,剩余元素放入新数组 const [first, second, ...rest] = arr; console.log(first); // 1 console.log(second); // 2 console.log(rest); // [3, 4, 5] // 跳过某些元素 const [a, , c, ...others] = arr; console.log(a); // 1 console.log(c); // 3 console.log(others); // [4, 5] 2.数组合并与插入 const arr1 = [1, 2, 3]; const arr2 = [4, 5, 6]; // 合并数组 const merged = [...arr1, ...arr2]; console.log(merged); // [1, 2, 3, 4, 5, 6] // 在特定位置插入元素 const newArr = [...arr1.slice(0, 1), 99, ...arr1.slice(1)]; console.log(newArr); // [1, 99, 2, 3] 3.函数参数处理 function processNumbers(first, second, ...rest) { console.log('前两个:', first, second); console.log('剩余:', rest); return [...rest, first, second]; } const result = processNumbers(1, 2, 3, 4, 5); // 前两个: 1 2 // 剩余: [3, 4, 5] console.log(result); // [3, 4, 5, 1, 2] 4.数组去重 const duplicates = [1, 2, 2, 3, 4, 4, 5]; const unique = [...new Set(duplicates)]; console.log(unique); // [1, 2, 3, 4, 5] 5.数组复制与修改 const original = [1, 2, 3]; // 浅拷贝 const copy = [...original]; console.log(copy); // [1, 2, 3] // 添加新元素 const withNew = [0, ...original, 4]; console.log(withNew); // [0, 1, 2, 3, 4] // 删除第一个元素 const [, ...withoutFirst] = original; console.log(withoutFirst); // [2, 3] 二、对象应用示例 1.基本解构+扩展 const user = { id: 1, name: '张三', age: 25, email: 'zhang@example.com' }; // 提取特定属性,剩余属性放入新对象 const { name, age, ...userInfo } = user; console.log(name); // '张三' console.log(age); // 25 console.log(userInfo); // {id: 1, email: 'zhang@example.com'} 2.对象合并与覆盖 const baseInfo = { name: '张三', age: 25 }; const contactInfo = { email: 'zhang@example.com', phone: '13800138000' }; // 合并对象 const user = { ...baseInfo, ...contactInfo }; console.log(user); // {name: '张三', age: 25, email: 'zhang@example.com', phone: '13800138000'} // 属性覆盖(后面的覆盖前面的) const updatedUser = { ...user, age: 26, city: '北京' }; console.log(updatedUser); // {name: '张三', age:
阅读全文