我有那个代码:
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 函数会改变原始数组吗?
我有那个代码:
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 函数会改变原始数组吗?
用于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();
它对数组进行原地排序(修改数组)。来自MDN:
sort() 方法就地对数组的元素进行排序并返回数组。排序不一定稳定。默认排序顺序是根据字符串 Unicode 代码点。
是的,它修改了原始数组。
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
或者来自 ES6:
const a = [1, 2, 3];
const b = [...a].sort();