如何在不改变原始数组的情况下对数组进行排序? [英] How can you sort an array without mutating the original array?
本文介绍了如何在不改变原始数组的情况下对数组进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我想要一个sort函数,它返回输入数组的排序副本。我天真地试过这个
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();
}
我用它测试了它,这表明我的 sort
方法正在改变数组。
and I tested it with this, which shows that my sort
method is mutating the array.
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"
我也试过这种方法
function sort(arr) {
return Array.prototype.sort(arr);
}
但它根本不起作用。
是否有一种直接的解决方法,优选的方式是不需要手动滚动我自己的排序算法或将数组的每个元素复制到一个新的元素中?
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?
推荐答案
只需复制数组即可。有很多方法可以做到这一点:
Just copy the array. There are many ways to do that:
function sort(arr) {
return arr.concat().sort();
}
// Or:
return Array.prototype.slice.call(arr).sort(); // For array-like objects
这篇关于如何在不改变原始数组的情况下对数组进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文