原文地址:https://dev.to/bhagatparwinder/destructuring-arrays-1dkf
解构或者解构赋值是一个让我们可以对数组或对象进行拆包,然后把它们赋值给变量的语法。这篇文章将重温一下数组解构。
为了演示,我们一起来看一个例子。我们将创建一个函数然后接受数字数组并打印那些数字。
const myNumbers = (arrOfNumbers) => {
const a = arrOfNumbers[0];
const b = arrOfNumbers[1];
const c = arrOfNumbers[2];
const d = arrOfNumbers[3];
const e = arrOfNumbers[4];
const f = arrOfNumbers[5];
const g = arrOfNumbers[6];
console.log(a, b, c, d, e, f, g)
}
myNumbers([7, 2, 19, 4000, 12, 45, -17]); // 7 2 19 4000 12 45 -17
上面的代码没有问题,但是我们必须为数组的每个元素赋值一个变量,有很多重复代码。你可以使用循环来减少一些代码:
const myNumbers = (arrOfNumbers) => {
arrOfNumbers.forEach((value) => {
console.log(value);
})
}
myNumbers([7, 2, 19, 4000, 12, 45, -17]); // 7, 2, 19, 4000, 12, 45, -17
循环没有问题但是我们却向代码中添加了逻辑。
解构使代码简洁:
const myNumbers = (arrOfNumbers) => {
const [a, b, c, d, e, f, g] = arrOfNumbers;
console.log(a, b, c, d, e, f, g); // 7 2 19 4000 12 45 -17
}
myNumbers([7, 2, 19, 4000, 12, 45, -17]);
就是这么简单,解构使左侧的表达式与右侧对应并按顺序赋值。
左右两侧并不总是长度对等,在这种情况下我们可以赋予默认值:
let a, b;
[a=19, b=-17] = [1];
console.log(a); // 1
console.log(b); // -17
为 a 赋值 1,由于数组只有一个值,所以 b 只能取默认值 -17。当右侧有额外的值时,将会被忽略。
let a, b;
[a = 19, b = -17] = [1, 2, 3,];
console.log(a); // 1
console.log(b); // 2
let a = 5;
let b = 15;
[a, b] = [b, a];
console.log(a); // 15
console.log(b); // 5
function foo() {
return [1, 2];
}
let a, b;
[a, b] = foo();
console.log(a); // 1
console.log(b); // 2
有时候你想获取的值并不是连续的,我们可以跳过中间的值:
function foo() {
return [1, 2, 3, 4];
}
let a, b;
[a, , , b] = foo();
console.log(a); // 1
console.log(b); // 4
当我们把解构和字符串一起使用的时候,split 方法很方便。
const [firstName, lastName] = "Parwinder Bhagat".split(' ');
console.log(firstName); // Parwinder
console.log(lastName); // Bhagat
let user = {};
[user.firstName, user.lastName] = ["Parwinder", "Bhagat"];
console.log(user); // { firstName: 'Parwinder', lastName: 'Bhagat' }
如果你想前面几个值单独赋值,后面的想归为一起,可以使用解构和扩展运算符一起使用来达到效果:
let [name1, name2, ...remaining] = ["Parwinder", "Lauren", "George", "Eliu", "Gaurav"];
console.log(name1); // Parwinder
console.log(name2); // Lauren
console.log(remaining.length); // 3
console.log(remaining[0]); // George
console.log(remaining); // [ 'George', 'Eliu', 'Gaurav' ]