在这种情况下,为什么要对原件进行分类修改?
问题描述:
我遇到了一个问题,那就是要更改原始数组,奇怪的是,添加arr.join("...").split("...")
似乎可以防止这种情况:
I had a problem that was making the original array to change, the curious thing is that adding arr.join("...").split("...")
seems to prevent this:
一些背景:
- 我的脚本创建并向
array
添加内容
- 此数组初始化为空,如
arr=[]
- 事物通过
arr[index] = "..."
添加
- 然后我想复制一份
arr
但已排序的 - 当我进行排序时,原始的
arr
被修改
- my script creates and adds stuff to an
array
- this array initialized empty like
arr=[]
- the things are added passing
arr[index] = "..."
- then I want to have a copy of the
arr
but sorted - when I do the sorting, the orignial
arr
is modified
这是正在发生的事情的简化版本:
Here is a simplified version of what is going on:
var arr=[], sorted;
arr[0] = "hello";
arr[1] = "world";
//buggy, the original is sorted
//sorted = arr.sort(function(a,b){return (a.length-b.length);});
sorted = arr.join("improbableCollision").split("improbableCollision").sort(function(a,b){return (a.length-b.length);});
- 为什么添加
.join("*").split("*")
可以解决问题? - 是什么原因引起的问题?
- 是否有更优雅的方法来解决此问题?
- Why adding
.join("*").split("*")
solves the problem? - What was causing the problem?
- Is there a more elegant way to fix this?
有关完整脚本,请检查此 jsFiddle
For the full script, check this jsFiddle
答
要在不进行所有合并和拆分的情况下进行排序,请使用slice或concat复制数组:
To sort without all that joining and splitting, copy the array with slice or concat:
var sorted = arr.slice(0).sort()
var sorted = arr.slice(0).sort()