这个问题在这里已经有了答案:
Copy array by value
(35 个回答)
8 年前关闭。
我试图在排序之前保存数组的副本:
words_Array = ["Why", "doesnt", "this", "work?"];
var sortedWords_Array = words_Array;
sortedWords_Array.sort(function(a, b){
return b.length - a.length;
});
alert("sortedWords_Array is :"+sortedWords_Array);
alert("words_Array is :"+words_Array);
在我对 sortedWords_Array 进行排序之后,它们都出于某种原因进行了排序。 http://jsfiddle.net/zv39J/这是为什么?
最佳答案
因为在 javascript 中,数组是通过引用传递的,这意味着当您使一个数组等于另一个数组时,只要您对一个数组进行编辑,它就会同时更改。要在您的示例中解决此问题,请更改以下行:
var sortedWords_Array = words_Array;
到:
//make a copy of array by using slice
var sortedWords_Array = words_Array.slice(0);
有关其他用途和更深入的解释,请参见此处:
slice does not alter the original array, but returns a new "one level deep" copy that contains copies of the elements sliced from the original array.
Array.prototype.slice()
关于javascript - 如何在排序之前保存数组的副本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20027207/