gpt4 book ai didi

javascript - ES2015+ Nested Rest 解释

转载 作者:数据小太阳 更新时间:2023-10-29 06:00:30 25 4
gpt4 key购买 nike

我正在查看 node.greendestructuring, assignment> nested rest下,使用了以下示例函数:

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; 返回 [1, 2, 1]

最佳答案

[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]

关于javascript - ES2015+ Nested Rest 解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39277588/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com