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

一、数组应用示例

这些示例展示了 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: 26, email: 'zhang@example.com', phone: '13800138000', city: '北京'}

3.排除特定属性

复制代码
const product = {
  id: 1,
  name: '手机',
  price: 2999,
  category: '电子产品',
  createTime: '2023-01-01'
};

// 排除敏感信息
const { price, createTime, ...publicInfo } = product;
console.log(publicInfo); // {id: 1, name: '手机', category: '电子产品'}

// 函数参数过滤
function createPublicProfile({ password, token, ...profile }) {
  return {
    ...profile,
    public: true
  };
}

const userData = { name: '张三', password: '123', token: 'abc' };
const publicProfile = createPublicProfile(userData);
console.log(publicProfile); // {name: '张三', public: true}

4.默认值与覆盖

复制代码
const defaultSettings = {
  theme: 'light',
  language: 'zh-CN',
  fontSize: 14
};

const userSettings = {
  theme: 'dark',
  notifications: true
};

// 合并默认设置和用户设置
const finalSettings = {
  ...defaultSettings,
  ...userSettings
};
console.log(finalSettings);
// {theme: 'dark', language: 'zh-CN', fontSize: 14, notifications: true}

5.嵌套对象处理

复制代码
const company = {
  name: 'ABC公司',
  address: {
    city: '北京',
    street: '朝阳路',
    zipcode: '100000'
  },
  employees: ['张三', '李四']
};

// 浅拷贝(嵌套对象仍是引用)
const shallowCopy = { ...company };

// 深拷贝嵌套对象
const deepCopy = {
  ...company,
  address: { ...company.address },
  employees: [...company.employees]
};

// 修改嵌套属性
const updatedCompany = {
  ...company,
  address: {
    ...company.address,
    city: '上海'  // 只修改city,其他地址属性保持不变
  }
};

三、数组和对象混合应用

1.处理API响应数据

复制代码
// 模拟API响应
const apiResponse = {
  data: {
    users: [
      { id: 1, name: '张三', role: 'admin' },
      { id: 2, name: '李四', role: 'user' }
    ]
  },
  status: 200,
  message: 'success'
};

// 提取用户数据并添加新用户
const { data: { users }, ...responseInfo } = apiResponse;
const newUser = { id: 3, name: '王五', role: 'user' };
const updatedUsers = [...users, newUser];

console.log(updatedUsers);
// [{id:1,name:'张三',role:'admin'}, {id:2,name:'李四',role:'user'}, {id:3,name:'王五',role:'user'}]

2.函数参数处理

复制代码
function createUser({ password, confirmPassword, ...userData }) {
  // 验证密码
  if (password !== confirmPassword) {
    throw new Error('密码不匹配');
  }
  
  return {
    ...userData,
    id: Date.now(),
    createTime: new Date().toISOString()
  };
}

const formData = {
  name: '张三',
  email: 'zhang@example.com',
  password: '123456',
  confirmPassword: '123456'
};

const newUser = createUser(formData);
console.log(newUser);
// {name: '张三', email: 'zhang@example.com', id: 1672531200000, createTime: '2023-01-01T00:00:00.000Z'}

3.状态更新(Rect/Vue)

复制代码
// React 状态更新示例
const [state, setState] = useState({
  user: { name: '张三', age: 25 },
  loading: false,
  data: []
});

// 更新用户年龄
setState(prevState => ({
  ...prevState,
  user: {
    ...prevState.user,
    age: 26
  }
}));

// Vue 数据更新
this.form = {
  ...this.form,
  user: {
    ...this.form.user,
    age: 26
  }
};

4.数据处理管道

复制代码
const products = [
  { id: 1, name: '手机', price: 2999, category: 'electronics' },
  { id: 2, name: '书本', price: 39, category: 'books' },
  { id: 3, name: '电脑', price: 5999, category: 'electronics' }
];

// 过滤、映射、排序
const processedProducts = products
  .filter(({ category }) => category === 'electronics')
  .map(({ price, ...product }) => ({
    ...product,
    price: price * 0.9, // 打9折
    discounted: true
  }))
  .sort((a, b) => a.price - b.price);

console.log(processedProducts);