找回密码
 立即注册
首页 业界区 业界 解构赋值+扩展运算符在数组和对象上的应用例子 ...

解构赋值+扩展运算符在数组和对象上的应用例子

桂册 2025-11-27 16:25:02
一、数组应用示例
这些示例展示了 ES6 解构赋值和扩展运算符的强大功能,它们让代码更加简洁、可读性更强
1.基本解构+扩展
  1. const arr = [1, 2, 3, 4, 5];
  2. // 获取前两个元素,剩余元素放入新数组
  3. const [first, second, ...rest] = arr;
  4. console.log(first);  // 1
  5. console.log(second); // 2
  6. console.log(rest);   // [3, 4, 5]
  7. // 跳过某些元素
  8. const [a, , c, ...others] = arr;
  9. console.log(a);      // 1
  10. console.log(c);      // 3
  11. console.log(others); // [4, 5]
复制代码
2.数组合并与插入
  1. const arr1 = [1, 2, 3];
  2. const arr2 = [4, 5, 6];
  3. // 合并数组
  4. const merged = [...arr1, ...arr2];
  5. console.log(merged); // [1, 2, 3, 4, 5, 6]
  6. // 在特定位置插入元素
  7. const newArr = [...arr1.slice(0, 1), 99, ...arr1.slice(1)];
  8. console.log(newArr); // [1, 99, 2, 3]
复制代码
3.函数参数处理
  1. function processNumbers(first, second, ...rest) {
  2.   console.log('前两个:', first, second);
  3.   console.log('剩余:', rest);
  4.   return [...rest, first, second];
  5. }
  6. const result = processNumbers(1, 2, 3, 4, 5);
  7. // 前两个: 1 2
  8. // 剩余: [3, 4, 5]
  9. console.log(result); // [3, 4, 5, 1, 2]
复制代码
4.数组去重
  1. const duplicates = [1, 2, 2, 3, 4, 4, 5];
  2. const unique = [...new Set(duplicates)];
  3. console.log(unique); // [1, 2, 3, 4, 5]
复制代码
5.数组复制与修改
  1. const original = [1, 2, 3];
  2. // 浅拷贝
  3. const copy = [...original];
  4. console.log(copy); // [1, 2, 3]
  5. // 添加新元素
  6. const withNew = [0, ...original, 4];
  7. console.log(withNew); // [0, 1, 2, 3, 4]
  8. // 删除第一个元素
  9. const [, ...withoutFirst] = original;
  10. console.log(withoutFirst); // [2, 3]
复制代码
二、对象应用示例
1.基本解构+扩展
  1. const user = {
  2.   id: 1,
  3.   name: '张三',
  4.   age: 25,
  5.   email: 'zhang@example.com'
  6. };
  7. // 提取特定属性,剩余属性放入新对象
  8. const { name, age, ...userInfo } = user;
  9. console.log(name);     // '张三'
  10. console.log(age);      // 25
  11. console.log(userInfo); // {id: 1, email: 'zhang@example.com'}
复制代码
2.对象合并与覆盖
  1. const baseInfo = { name: '张三', age: 25 };
  2. const contactInfo = { email: 'zhang@example.com', phone: '13800138000' };
  3. // 合并对象
  4. const user = { ...baseInfo, ...contactInfo };
  5. console.log(user);
  6. // {name: '张三', age: 25, email: 'zhang@example.com', phone: '13800138000'}
  7. // 属性覆盖(后面的覆盖前面的)
  8. const updatedUser = { ...user, age: 26, city: '北京' };
  9. console.log(updatedUser);
  10. // {name: '张三', age: 26, email: 'zhang@example.com', phone: '13800138000', city: '北京'}
复制代码
3.排除特定属性
  1. const product = {
  2.   id: 1,
  3.   name: '手机',
  4.   price: 2999,
  5.   category: '电子产品',
  6.   createTime: '2023-01-01'
  7. };
  8. // 排除敏感信息
  9. const { price, createTime, ...publicInfo } = product;
  10. console.log(publicInfo); // {id: 1, name: '手机', category: '电子产品'}
  11. // 函数参数过滤
  12. function createPublicProfile({ password, token, ...profile }) {
  13.   return {
  14.     ...profile,
  15.     public: true
  16.   };
  17. }
  18. const userData = { name: '张三', password: '123', token: 'abc' };
  19. const publicProfile = createPublicProfile(userData);
  20. console.log(publicProfile); // {name: '张三', public: true}
复制代码
4.默认值与覆盖
  1. const defaultSettings = {
  2.   theme: 'light',
  3.   language: 'zh-CN',
  4.   fontSize: 14
  5. };
  6. const userSettings = {
  7.   theme: 'dark',
  8.   notifications: true
  9. };
  10. // 合并默认设置和用户设置
  11. const finalSettings = {
  12.   ...defaultSettings,
  13.   ...userSettings
  14. };
  15. console.log(finalSettings);
  16. // {theme: 'dark', language: 'zh-CN', fontSize: 14, notifications: true}
复制代码
5.嵌套对象处理
  1. const company = {
  2.   name: 'ABC公司',
  3.   address: {
  4.     city: '北京',
  5.     street: '朝阳路',
  6.     zipcode: '100000'
  7.   },
  8.   employees: ['张三', '李四']
  9. };
  10. // 浅拷贝(嵌套对象仍是引用)
  11. const shallowCopy = { ...company };
  12. // 深拷贝嵌套对象
  13. const deepCopy = {
  14.   ...company,
  15.   address: { ...company.address },
  16.   employees: [...company.employees]
  17. };
  18. // 修改嵌套属性
  19. const updatedCompany = {
  20.   ...company,
  21.   address: {
  22.     ...company.address,
  23.     city: '上海'  // 只修改city,其他地址属性保持不变
  24.   }
  25. };
复制代码
三、数组和对象混合应用
1.处理API响应数据
  1. // 模拟API响应
  2. const apiResponse = {
  3.   data: {
  4.     users: [
  5.       { id: 1, name: '张三', role: 'admin' },
  6.       { id: 2, name: '李四', role: 'user' }
  7.     ]
  8.   },
  9.   status: 200,
  10.   message: 'success'
  11. };
  12. // 提取用户数据并添加新用户
  13. const { data: { users }, ...responseInfo } = apiResponse;
  14. const newUser = { id: 3, name: '王五', role: 'user' };
  15. const updatedUsers = [...users, newUser];
  16. console.log(updatedUsers);
  17. // [{id:1,name:'张三',role:'admin'}, {id:2,name:'李四',role:'user'}, {id:3,name:'王五',role:'user'}]
复制代码
2.函数参数处理
  1. function createUser({ password, confirmPassword, ...userData }) {
  2.   // 验证密码
  3.   if (password !== confirmPassword) {
  4.     throw new Error('密码不匹配');
  5.   }
  6.   
  7.   return {
  8.     ...userData,
  9.     id: Date.now(),
  10.     createTime: new Date().toISOString()
  11.   };
  12. }
  13. const formData = {
  14.   name: '张三',
  15.   email: 'zhang@example.com',
  16.   password: '123456',
  17.   confirmPassword: '123456'
  18. };
  19. const newUser = createUser(formData);
  20. console.log(newUser);
  21. // {name: '张三', email: 'zhang@example.com', id: 1672531200000, createTime: '2023-01-01T00:00:00.000Z'}
复制代码
3.状态更新(Rect/Vue)
  1. // React 状态更新示例
  2. const [state, setState] = useState({
  3.   user: { name: '张三', age: 25 },
  4.   loading: false,
  5.   data: []
  6. });
  7. // 更新用户年龄
  8. setState(prevState => ({
  9.   ...prevState,
  10.   user: {
  11.     ...prevState.user,
  12.     age: 26
  13.   }
  14. }));
  15. // Vue 数据更新
  16. this.form = {
  17.   ...this.form,
  18.   user: {
  19.     ...this.form.user,
  20.     age: 26
  21.   }
  22. };
复制代码
4.数据处理管道
  1. const products = [
  2.   { id: 1, name: '手机', price: 2999, category: 'electronics' },
  3.   { id: 2, name: '书本', price: 39, category: 'books' },
  4.   { id: 3, name: '电脑', price: 5999, category: 'electronics' }
  5. ];
  6. // 过滤、映射、排序
  7. const processedProducts = products
  8.   .filter(({ category }) => category === 'electronics')
  9.   .map(({ price, ...product }) => ({
  10.     ...product,
  11.     price: price * 0.9, // 打9折
  12.     discounted: true
  13.   }))
  14.   .sort((a, b) => a.price - b.price);
  15. console.log(processedProducts);
复制代码
 

来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

相关推荐

您需要登录后才可以回帖 登录 | 立即注册