Let's suppose I wanted a sort function that returns a sorted copy of the inputted array.(假设我想要一个排序函数,该函数返回输入数组的排序副本。)
I naively tried this(我天真地尝试过)
function sort(arr) {
return arr.sort();
}
and I tested it with this, which shows that my sort
method is mutating the array.(我对此进行了测试,这表明我的sort
方法正在使数组变异。)
var a = [2,3,7,5,3,7,1,3,4];
sort(a);
alert(a); //alerts "1,2,3,3,3,4,5,7,7"
I also tried this approach(我也尝试过这种方法)
function sort(arr) {
return Array.prototype.sort(arr);
}
but it doesn't work at all.(但它根本不起作用。)
Is there a straightforward way around this, prefereably a way that doesn't require hand-rolling my own sorting algorithm or copying every element of the array into a new one?(有没有解决此问题的简单方法,最好是不需要手动滚动我自己的排序算法或将数组的每个元素复制到一个新元素中的方法?)
ask by Peter Olson translate from so
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…