.sort函数是否会更改原始数组?

Pro*_*der 9 javascript arrays sorting

我有那个代码:

arr = arr.sort(function (a, b) {
    return a.time>b.time
})
Run Code Online (Sandbox Code Playgroud)

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

arr.sort(function (a, b) {
    return a.time>b.time
})
Run Code Online (Sandbox Code Playgroud)

排序和过滤功能会改变原始数组吗?

Lex*_*obs 25

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

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

arr.sort(function (a, b) {
  return a.time-b.time;
});
Run Code Online (Sandbox Code Playgroud)

将改变原始数组并返回:

[{时间: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;
});
Run Code Online (Sandbox Code Playgroud)

回报

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

但不会影响原始数组.

console.log(arr)返回

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


Ale*_*lls 8

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

const a = [1,2,3];
const b = a.sort();
console.log(a === b); // true
Run Code Online (Sandbox Code Playgroud)

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

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

   const a = [1,2,3];
   const b = a.slice(0).sort();
Run Code Online (Sandbox Code Playgroud)

  • 是的!sort() 改变原始数组。filter() 函数创建一个过滤后的副本,保持原件完好无损。见 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter (5认同)

jfr*_*d00 6

它对数组进行了排序(修改数组).来自MDN:

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


SUS*_*LAL 5

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

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
Run Code Online (Sandbox Code Playgroud)