ES2015+ Nested Rest 解释

ES2015+ Nested Rest explanation

我正在查看 node.green 并且在 解构、赋值 > 嵌套剩余 下,使用了以下示例函数:

function f() {
  var a = [1, 2, 3], first, last;
  [first, ...[a[2], last]] = a;
  return first === 1 && last === 3 && (a + "") === "1,2,2";
}

console.log(f())

现在,我理解了解构,但我不明白为什么 a 被重写为 [1, 2, 2]

还有[...[a[2], last]] = a;returns[1, 2, 1]

在第二行中,您将 a[2] 设置为 a 的第二个值,即 a[1],在本例中为 2

有意思的是,如果把[first, ...[a[2], last]]改成[first, a[2], last]last就变成了2(firsta的最终值是一样的你的例子):

var a = [1, 2, 3], first, last;
[first, a[2], last] = a;

console.log(first === 1);
console.log(a + '' === '1,2,2');
console.log(last === 2);

看起来 a[2] 首先被赋值 2,然后 last 被赋值 a[2]。在您的示例中,似乎保留了 a 的旧值。我怀疑这是因为 ... 创建了一个中间数组,然后将其值分配给 a[2]last。希望深入了解 ES6 规范的人可以确认,但大概这就是更复杂的原因 [first, ...[a[2], last]].

更新

Bergi 在评论中分享了规范参考:

see IteratorBindingInitialization, with BindingRestElement. However, the usage of a BindingPattern instead of a simple BindingIdentifier is actually new in ES7. In ES6 you'd need to write var [first, ...tmp] = a; [a[2], last]] = tmp; which makes clearer what is happening.

[first, a[2], last] = a;

就像

// first == undefined,   last == undefined,   a == [1,2,3]
first = a[0];
// first == 1,           last == undefined,   a == [1,2,3]
a[2] = a[1];
// first == 1,           last == undefined,   a == [1,2,2]
last = a[2];
// first == 1,           last == 2,           a == [1,2,2]

[first, ...[a[2], last]] = a;

就像

// first == undefined,   last == undefined,   a == [1,2,3],   tmp == undefined
first = a[0];
// first == 1,           last == undefined,   a == [1,2,3],   tmp == undefined
tmp = [a[1], a[2]];
// first == 1,           last == undefined,   a == [1,2,3],   tmp == [2,3]
a[2] = tmp[0];
// first == 1,           last == undefined,   a == [1,2,2],   tmp == [2,3]
last = tmp[1];
// first == 1,           last == 3,           a == [1,2,2],   tmp == [2,3]

[...[a[2], last]] = a;

就像

// last == undefined,   a == [1,2,3],   tmp == undefined
tmp = [a[0], a[1]];
// last == undefined,   a == [1,2,3],   tmp == [1,2]
a[2] = tmp[0];
// last == undefined,   a == [1,2,1],   tmp == [1,2]
last = tmp[1];
// last == 2,           a == [1,2,1],   tmp == [1,2]