繁体   English   中英

ES6:使用解构分配交换不直观的数组元素

[英]ES6: Unintuitive array element swapping using destructuring assignment

尝试使用解构分配交换元素来对数组进行排序:

排序后的数组应为整数[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

这是一个nodejs REPL

似乎先缓存了=右边的值,然后按从左到右的顺序执行每个赋值。 如果后面的分配取决于先前分配的值,则将导致不直观的结果

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]

第一个示例给出了一个不直观的结果,因为a [0]在作为第二个赋值的一部分被访问之前已被修改。

交换分配顺序,以便在修改其值之前访问a [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]

暂无
暂无

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

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