我如何排序前保存数组的副本? [英] How do I save a copy of an array before sorting?

查看:118
本文介绍了我如何排序前保存数组的副本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将数组保存的副本之前,我对它进行排序:

I'm trying to save a copy of the array before I sort it:

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中,数组是通过引用传递,这意味着,当你做一个阵列等于另一个它会改变两者每当你编辑一个。要在你的榜样解决这个更改以下行:

Because in javascript, arrays are passed by reference which means that when you make one array equal to another it will change both whenever you make an edit to one. To fix this in your example change the following line:

var sortedWords_Array = words_Array;

 //make a copy of array by using slice
 var sortedWords_Array = words_Array.slice(0);

在这里看到其他用途和更深入的解释:

See here for other uses and a more in-depth explanation:

片不会改变原来的数组,但返回一个新的一平
  深副本包含从切片元素的副本
  原始数组。

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()

这篇关于我如何排序前保存数组的副本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆