面试题面试题面试题之node.js(一)
2ChaosJavaScript 中的解构赋值与拓展运算符 ... 的用法
JavaScript 中的解构赋值和拓展运算符 ... 是 ES6 中引入的非常强大的特性,它们能够简化代码并提高可读性。下面分别介绍它们的用法。
解构赋值
解构赋值可以从数组或对象中提取值,然后赋值给变量。
数组解构赋值
1 2 3 4 5 6 7 8
| const array = [1, 2, 3];
const [a, b, c] = array;
console.log(a); console.log(b); console.log(c);
|
对象解构赋值
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); console.log(age); console.log(city);
|
拓展运算符 ...
拓展运算符 ... 可以在数组和对象中使用,主要用于拷贝、合并以及传递不定数量的参数。
数组中的拓展运算符
拷贝数组
1 2 3 4
| const array1 = [1, 2, 3]; const array2 = [...array1];
console.log(array2);
|
合并数组
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
| function sum(...numbers) { return numbers.reduce((total, num) => total + num, 0); }
console.log(sum(1, 2, 3));
|
对象中的拓展运算符
拷贝对象
1 2 3 4
| const person1 = { name: "John", age: 30 }; const person2 = { ...person1 };
console.log(person2);
|
合并对象
1 2 3 4 5
| const person1 = { name: "John", age: 30 }; const job = { title: "Developer", company: "XYZ" }; const personWithJob = { ...person1, ...job };
console.log(personWithJob);
|
解构赋值与拓展运算符结合使用
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); console.log(age); console.log(rest);
|