JS 解构赋值
warning:
这篇文章距离上次修改已过266天,其中的内容可能已经有所变动。
解构赋值是一种表达式,它允许我们将数组或对象的值解压到不同的变量中。在JavaScript中,解构赋值可以用于数组、对象、字符串、以及函数参数。
数组解构
let [a, b, c] = [1, 2, 3];
console.log(a); // 输出1
console.log(b); // 输出2
// 可以使用rest运算符获取剩余元素
let [x, ...rest] = [1, 2, 3, 4];
console.log(rest); // 输出[2, 3, 4]
// 可以设置默认值,当数组中的值为undefined时,会使用默认值
let [a = 5, b = 7] = [undefined, 2];
console.log(a); // 输出5
console.log(b); // 输出2
对象解构
let {x, y} = {x: 1, y: 2};
console.log(x); // 输出1
console.log(y); // 输出2
// 可以使用别名
let {x: a, y: b} = {x: 1, y: 2};
console.log(a); // 输出1
console.log(b); // 输出2
// 可以设置默认值
let {x = 5, y = 7} = {x: 1};
console.log(x); // 输出1
console.log(y); // 输出7
字符串解构
const [a, b, c] = 'abc';
console.log(a); // 输出'a'
console.log(b); // 输出'b'
函数参数解构
function add([x, y]) {
return x + y;
}
console.log(add([1, 2])); // 输出3
// 使用剩余参数
function subtract(...[a, b]) {
return a - b;
}
console.log(subtract(1, 2, 3)); // 输出-1
以上是解构赋值的一些基本用法,它可以极大地简化代码,提高开发效率。
评论已关闭