简体   繁体   English

Swap 使用 Javascript/ES6 解构赋值不按预期工作

[英]Swap Using Javascript/ES6 Destructuring Assignment Not Working As Intended

I thought that JavaScript ES6 Swap destructuring assignment is an order-independent operation.我认为 JavaScript ES6 Swap 解构赋值是一个与顺序无关的操作。 The below, when executed both on chromium and Firefox, give the same (seemingly) wrong result.下面,在 Chrome 和 Firefox 上执行时,给出相同(看似)错误的结果。 Since it is unlikely that both Chromium and Firefox have the same bug, I wonder if I am not understanding something right.由于 Chromium 和 Firefox 不太可能有相同的错误,我想知道我是否理解错误。 Can you help understand why this is so, please?你能帮助理解为什么会这样吗?

Code:代码:

let node3 = {id: 3, next: null};
let node2 = {id: 2, next: node3};
let node1 = {id: 1, next: node2};

[node1.next, node1] = [null, node1.next];
console.log(`${node1} ${node1?.id}, ${node1?.next?.id}`);

Result (node1.next points to node3):结果(node1.next 指向 node3):

 [object Object] 2, 3

Same code (just with the assignment order reversed):相同的代码(只是分配顺序颠倒了):

let node3 = {id: 3, next: null};
let node2 = {id: 2, next: node3};
let node1 = {id: 1, next: node2};

[node1, node1.next] = [node1.next, null];
console.log(`${node1} ${node1?.id}, ${node1?.next?.id}`);

Result (node1.next now is null!):结果(node1.next 现在为空!):

[object Object] 2, **undefined**

You seem to be misunderstanding the destructuring logic.你似乎误解了解构逻辑。 Your example breaks down (with a little hand-waving) as您的示例分解(稍微挥手)为

let node3 = {id: 3, next: null};
let node2 = {id: 2, next: node3};
let node1 = {id: 1, next: node2};

// [node1.next, node1] = [null, node1.next];
let tmp = [null, node1.next];
node1.next = tmp[0];
node1 = tmp[1];
console.log(`${node1} ${node1?.id}, ${node1?.next?.id}`);

and your second swaps the two tmp lines to be你的第二个交换了两条tmp

// [node1, node1.next] = [node1.next, null];
let tmp = [node1.next, null];
node1 = tmp[0];
node1.next = tmp[1];

This second one fails because you're essentially now doing第二个失败了,因为你现在基本上在做

let node1Next = node1.next;
node1 = node1Next;
node1.next = null;

where the first, functional, example is doing第一个功能性示例在做什么

let node1Next = node1.next;
node1.next = null;
node1 = node1Next;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM