我正在检查
node.green并在解构,分配>嵌套休息,使用以下示例函数:
function f() { var a = [1,2,3],first,last; [first,...[a[2],last]] = a; return first === 1 && last === 3 && (a + "") === "1,2"; } console.log(f())
现在,我理解解构,但我无法弄清楚为什么a被重写为[1,2]
另外[… [a [2],last]] = a;返回[1,1]
解决方法
[first,a[2],last] = a;
就好像
// first == undefined,last == undefined,a == [1,3] first = a[0]; // first == 1,3] a[2] = a[1]; // first == 1,2] last = a[2]; // first == 1,last == 2,2]
[first,last]] = a;
就好像
// first == undefined,tmp == undefined first = a[0]; // first == 1,tmp == undefined tmp = [a[1],a[2]]; // first == 1,tmp == [2,3] a[2] = tmp[0]; // first == 1,2],3] last = tmp[1]; // first == 1,last == 3,3]
[...[a[2],last]] = a;
就好像
// last == undefined,tmp == undefined tmp = [a[0],a[1]]; // last == undefined,tmp == [1,2] a[2] = tmp[0]; // last == undefined,1],2] last = tmp[1]; // last == 2,2]