Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
375 views
in Technique[技术] by (71.8m points)

javascript - 如何在不更改原始数组的情况下对数组进行排序?(How can you sort an array without mutating the original array?)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...