面试题之es6(一)

JavaScript 中的解构赋值与拓展运算符 ... 的用法

JavaScript 中的解构赋值和拓展运算符 ... 是 ES6 中引入的非常强大的特性,它们能够简化代码并提高可读性。下面分别介绍它们的用法。

解构赋值

解构赋值可以从数组或对象中提取值,然后赋值给变量。

数组解构赋值
1
2
3
4
5
6
7
8
const array = [1, 2, 3];

// 使用解构赋值从数组中提取值
const [a, b, c] = array;

console.log(a); // 1
console.log(b); // 2
console.log(c); // 3
对象解构赋值
1
2
3
4
5
6
7
8
9
10
11
12
const person = {
name: "John",
age: 30,
city: "New York",
};

// 使用解构赋值从对象中提取值
const { name, age, city } = person;

console.log(name); // John
console.log(age); // 30
console.log(city); // New York

拓展运算符 ...

拓展运算符 ... 可以在数组和对象中使用,主要用于拷贝、合并以及传递不定数量的参数。

数组中的拓展运算符
拷贝数组
1
2
3
4
const array1 = [1, 2, 3];
const array2 = [...array1];

console.log(array2); // [1, 2, 3]
合并数组
1
2
3
4
5
const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
const mergedArray = [...array1, ...array2];

console.log(mergedArray); // [1, 2, 3, 4, 5, 6]
函数参数
1
2
3
4
5
function sum(...numbers) {
return numbers.reduce((total, num) => total + num, 0);
}

console.log(sum(1, 2, 3)); // 6
对象中的拓展运算符
拷贝对象
1
2
3
4
const person1 = { name: "John", age: 30 };
const person2 = { ...person1 };

console.log(person2); // { name: 'John', age: 30 }
合并对象
1
2
3
4
5
const person1 = { name: "John", age: 30 };
const job = { title: "Developer", company: "XYZ" };
const personWithJob = { ...person1, ...job };

console.log(personWithJob); // { name: 'John', age: 30, title: 'Developer', company: 'XYZ' }
解构赋值与拓展运算符结合使用
1
2
3
4
5
6
7
8
9
10
11
12
13
const person = {
name: "John",
age: 30,
city: "New York",
job: "Developer",
};

// 从对象中提取部分属性,其余的属性使用拓展运算符保留
const { name, age, ...rest } = person;

console.log(name); // John
console.log(age); // 30
console.log(rest); // { city: 'New York', job: 'Developer' }