javascript .sort 函数会改变原始数组吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24074968/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 02:08:56  来源:igfitidea点击:

Does .sort function change original array?

javascriptarrayssorting

提问by Prosto Trader

I have that code:

我有那个代码:

arr = arr.sort(function (a, b) {
    return a.time>b.time
})

Do I need to redefine arr or it is possible just to call sort function? like this:

我需要重新定义 arr 还是可以只调用 sort 函数?像这样:

arr.sort(function (a, b) {
    return a.time>b.time
})

Will the sort and filter functions change the original array?

sort 和 filter 函数会改变原始数组吗?

回答by LexJacobs

Use slice()to sort a copyof the original array.

用于slice()对原始数组的副本进行排序。

var arr =[{time:4},{time:3},{time:6}];

arr.sort(function (a, b) {
  return a.time-b.time;
});

will mutate the original array and returns :

将改变原始数组并返回:

[ { time: 3 }, { time: 4 }, { time: 6 } ]

[ { 时间: 3 }, { 时间: 4 }, { 时间: 6 } ]

and console.log(arr) returns

和 console.log(arr) 返回

[ { time: 3 }, { time: 4 }, { time: 6 } ]

[ { 时间: 3 }, { 时间: 4 }, { 时间: 6 } ]

but

var arr =[{time:4},{time:3},{time:6}];
arr.slice().sort(function (a, b) {
  return a.time-b.time;
});

returns

回报

[ { time: 3 }, { time: 4 }, { time: 6 } ]

[ { 时间: 3 }, { 时间: 4 }, { 时间: 6 } ]

but will not affect the original array.

但不会影响原始数组。

console.log(arr) returns

console.log(arr) 返回

[ { time: 4 }, { time: 3 }, { time: 6 } ]

[ { 时间: 4 }, { 时间: 3 }, { 时间: 6 } ]

回答by Alexander Mills

It's a decent question, and let's answer it properly:

这是一个不错的问题,让我们正确回答:

const a = [1,2,3];
const b = a.sort();
console.log(a === b); // true

there is your answer. The === operator for objects will compare memory locations, so it's the same object in memory. Which is a shame because it would be better if sort created a new array (immutability etc), but in many languages it does not return a new array, but the same array (reordered).

这就是你的答案。对象的 === 运算符将比较内存位置,因此它是内存中的相同对象。这是一种耻辱,因为如果 sort 创建一个新数组(不变性等)会更好,但在许多语言中它不会返回一个新数组,而是相同的数组(重新排序)。

So if you want it to be immutable, you can do:

因此,如果您希望它不可变,则可以执行以下操作:

   const a = [1,2,3];
   const b = a.slice(0).sort();

回答by jfriend00

It sorts the array in place (modifying the array). From MDN:

它对数组进行原地排序(修改数组)。来自MDN

The sort() method sorts the elements of an array in place and returns the array. The sort is not necessarily stable. The default sort order is according to string Unicode code points.

sort() 方法就地对数组的元素进行排序并返回数组。排序不一定稳定。默认排序顺序是根据字符串 Unicode 代码点。