MDN Web Docs 有这个例子:
使用绑定模式作为其余属性
数组解构赋值的rest属性可以是另一个数组或对象绑定模式。这允许您同时解包数组的属性和索引。
const [a, b, ...{ pop, push }] = [1, 2]; console.log(a, b); // 1 2 console.log(pop, push); // [Function pop] [Function push]
那些
pop
和push
功能是什么以及如何使用它们?
> pop()
Uncaught TypeError: Cannot convert undefined or null to object
at pop (<anonymous>)
> push(3)
Uncaught TypeError: Cannot convert undefined or null to object
at push (<anonymous>)
通过定期解构,您可以:
const obj = {a:3, b:4}
const {a} = obj // equivalent to const a = obj.a
现在考虑以下代码:
const [a, b, ...rest] = [1, 2];
console.log(a, b, rest); // 1 2 []
let {push, pop} = rest;
console.log(push, pop);
rest
将是一个包含第三个数字的数组。由于没有第三个数字,rest
将是一个空数组。
push
和 pop
是可以从数组对象中解构出来的函数。这解释了为什么 const [a, b, ...{ pop, push }] = [1, 2];
将从展开语法生成的空数组中提取 pop
和 push
函数。
由于您没有对传播语法创建的数组的引用,因此这些方法在您给出的示例中不是很有用。正如@pilchard 指出的那样,要调用这些方法中的任何一种,您需要使用
call
或 apply
以便 this
将被设置为特定的数组实例。
一个更有用的例子是获取数组中其他元素的数量(没有单独解构):
const [a, b, ...{length}] = [1, 2, 3, 4, 5]
console.log(length)