在做一道算法题的时候遇到一个问题。
1 2 3 4
| var a = [0, 1, 2, 3, 4]; var i = 0; [a[a[i]], a[a[i] + 1]] = [a[a[i] + 1], a[a[i]]]; console.log(a);
|
按理说这样应该数据互换,输出:
<
大专栏 解构赋值交换数据遇上的坑p>
但是实际上是输出的:
但是!如果我把代码改成:
1
| [a[a[i] + 1], a[a[i]]] = [a[a[i]], a[a[i] + 1]];
|
输出结果就变成了:
emm……
这个问题我想了下结果被绕进去了,搞不清赋值的顺序是怎么样的,暂时的结论就是不要在使用解构赋值对数组元素的值进行互换时使用数组元素本身做索引(好像也没有多少时候需要这样做)。