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

IT技术 javascript arrays sorting
2021-02-26 03:22:20

我有那个代码:

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

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

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

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

5个回答

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

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

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

将改变原始数组并返回:

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

和 console.log(arr) 返回

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

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

回报

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

但不会影响原始数组。

console.log(arr) 返回

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

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

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

这就是你的答案。===对象运算符将比较内存位置,因此它是内存中的相同对象。

这是一种耻辱,因为如果 sort 创建一个新数组(不变性等)会更好,但在许多语言中它不会返回一个新数组,而是相同的数组(重新排序)。

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

const a = [1, 2, 3];
const b = a.slice(0).sort();
事实上,我很喜欢它改变了原作。因为那样,你可以处理和解决这个问题。您无法解决“我想对这个数组进行排序,以便现有引用获得更新的数据”,但它们不会自动解决。想象一下,如果arr.push(4,5,6)没有改变原来的。那将是一场噩梦。您必须完全依赖arr = arr.concat([4,5,6]),并且仍然无法更新引用。
2021-04-30 03:22:20
是的!sort() 改变原始数组。filter() 函数创建一个过滤后的副本,保持原件完好无损。developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/...
2021-05-10 03:22:20

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

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

sort 的一个有趣的特性"undefined property values always sort to the end of the result, followed by non-existent property values",因此它有效地将稀疏数组更改为紧凑但保持原始长度。
2021-04-29 03:22:20

是的,它修改了原始数组。

const a = [1, 2, 3];
const b = a.sort();
const c = [...a].sort(); //es6 feauture similar to slice(0)
console.log(a === b); // true
console.log(a === c);//false
我会更喜欢这个,我认为它比 splice().sort() 有更好的性能
2021-04-27 03:22:20

或者来自 ES6:

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