Javascript ES6:使用非结构化赋值的非直观数组元素交换

Javascript ES6:使用非结构化赋值的非直观数组元素交换,javascript,node.js,ecmascript-6,Javascript,Node.js,Ecmascript 6,尝试通过使用交换元素对数组进行排序: 排序后的数组应该是整数的升序[1,2,…] // try to sort the array by swapping const a = [2, 1]; 为什么下面的代码没有按预期交换元素 // Swap the '2' with the number at its final position. [a[0], a[a[0]-1]] = [a[a[0]-1], a[0]]; console.log(a); // Result is still [2, 1

尝试通过使用交换元素对数组进行排序:

排序后的数组应该是整数的升序
[1,2,…]

// try to sort the array by swapping 
const a = [2, 1];
为什么下面的代码没有按预期交换元素

// Swap the '2' with the number at its final position.
[a[0], a[a[0]-1]] = [a[a[0]-1], a[0]];
console.log(a); // Result is still [2, 1]
但是,切换要交换的元素的顺序可以按预期工作

// Just changed the order of the two elements to be swapped
[a[a[0]-1], a[0]] = [a[0], a[a[0]-1]];
console.log(a); // Result is [1, 2] as expected

似乎先缓存=右侧的值,然后按从左到右的顺序执行每个赋值。 如果后一个赋值依赖于前一个赋值的值,这将导致不直观的结果

Babel将ES6代码编译为以下语句:

"use strict";

// try to sort the array by swapping elements
var a = [2, 1];

// does not work
var _ref = [a[a[0] - 1], a[0]];
a[0] = _ref[0];
a[a[0] - 1] = _ref[1];

console.log(a); // [2, 1]
第一个示例给出了一个不直观的结果,因为[0]在作为第二个赋值的一部分被访问之前被修改

交换赋值顺序,以便在修改[0]的值之前访问它,将产生正确的结果

// does work
var _ref2 = [a[0], a[a[0] - 1]];
a[a[0] - 1] = _ref2[0];
a[0] = _ref2[1];

console.log(a); // [1, 2]

你能不能把你的帖子改成一个问题的形式,并附上一些代码,而不是一个带有链接的代码块,其他什么都没有?(如果您还没有读过,请记住阅读,这里有一些关于发布到SO的可靠建议)这里有一个指向MDN的链接,它显示了使用解构进行交换的正确方法:您使用
a[0]-1]
作为索引吗?