在设置变量时对数组进行排序后,原始数组也会被排序

时间:2013-01-29 18:54:14

标签: javascript arrays sorting

  

可能重复:
  Why is sorting modifing the original in this case?

jsFiddle - 我有2个阵列。我想将第二个变量设置为第一个变量的排序版本。

var _myArray = ["N","T","A","W","Z","X"];
var _array02 = _myArray.sort();

document.write(_myArray+'<br>'+_array02);

应该发生什么:N,T,A,W,N,X<br>A,N,T,W,X,Z

反而会发生什么:A,N,T,W,X,Z<br>A,N,T,W,X,Z

这是JS的设计,如果是这样,我如何实现我的目标?

1 个答案:

答案 0 :(得分:5)

sort()对数组进行排序。如果您希望原始数组保持不变,请对副本进行排序:

var _myArray = ["N","T","A","W","Z","X"];
var _array02 = _myArray.slice().sort();

_myArray +'\n'+_array02

/*  returned value: (String)
N,T,A,W,Z,X
A,N,T,W,X,Z
*/