js解构赋值和...的运用

解构赋值

含义

在 JavaScript 中,解构赋值是一种方便的语法,用于从数组或对象中提取数据并赋值给变量

示例

  1. 解构数组:
    const numbers = [1, 2, 3, 4, 5];
    const [a, b, ...rest] = numbers;
    console.log(a); // 1
    console.log(b); // 2
    console.log(rest); // [3, 4, 5]
  2. 解构对象:
    const person = { name: 'John', age: 30, city: 'New York' };
    const { name, age } = person;
    console.log(name); // 'John'
    console.log(age); // 30

  3. 默认值:
    const numbers = [1];
    const [a, b = 2] = numbers;
    console.log(a); // 1
    console.log(b); // 2 (使用了默认值)

...的运用 

 合并数组:

const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const combined = [...arr1, ...arr2];
console.log(combined);
// 输出: [1, 2, 3, 4, 5, 6]

合并对象:

const obj1 = { a: 1, b: 2 };
const obj2 = { c: 3, d: 4 };
const combined = { ...obj1, ...obj2 };
console.log(combined);
// 输出: { a: 1, b: 2, c: 3, d: 4 }

复制对象:

const original = { a: 1, b: 2 };
const copy = { ...original };
console.log(copy);
// 输出: { a: 1, b: 2 }

追加元素到对象

const person = { name: 'John', age: 30 };
const updatedPerson = { ...person, city: 'New York' };
console.log(updatedPerson);
// 输出: { name: 'John', age: 30, city: 'New York' }

 

你可能感兴趣的:(javascript,开发语言,ecmascript)