我有这段代码:
arr = arr.sort(function (a, b) {
return a.time>b.time
})
我需要重新定义 arr 数组吗,还是直接调用排序函数就可以了?像这样:
arr.sort(function (a, b) {
return a.time>b.time
})
排序和过滤函数会改变原始数组吗?
我有这段代码:
arr = arr.sort(function (a, b) {
return a.time>b.time
})
我需要重新定义 arr 数组吗,还是直接调用排序函数就可以了?像这样:
arr.sort(function (a, b) {
return a.time>b.time
})
排序和过滤函数会改变原始数组吗?
使用slice()
对原始数组进行副本的排序。
var arr =[{time:4},{time:3},{time:6}];
arr.sort(function (a, b) {
return a.time-b.time;
});
会改变原始数组并返回:
[ { time: 3 }, { time: 4 }, { time: 6 } ]
而 console.log(arr) 返回的是:
[ { time: 3 }, { time: 4 }, { time: 6 } ]
但是
var arr =[{time:4},{time:3},{time:6}];
arr.slice().sort(function (a, b) {
return a.time-b.time;
});
返回
[ { time: 3 }, { time: 4 }, { time: 6 } ]
但不会影响原始数组。
console.log(arr) 返回
[ { time: 4 }, { time: 3 }, { time: 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])
,但仍然无法更新引用。 - RoboticRenaissance是的,它修改了原始数组。
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();
排序和过滤功能会改变原始数组吗?
对于 sort() 方法,答案是 是的
,但对于 filter() 方法,答案是 不会
。
让我用一个例子来解释 :
// Original Array
const arr = [5, 4, 3, 2, 1];
// Sorting array values and assigned in a variable.
const sortedArr = arr.sort((a, b) => a-b);
// Original array modified.
console.log(arr); // [1,2,3,4,5]
// New variable with sorted array.
console.log(sortedArr); // [1,2,3,4,5]
to[操作]
方法,它返回一个应用了该操作的新集合(目前处于第三阶段,即将可用)。const arr = [5, 4, 3, 2, 1];
const sortedArr = arr.toSort((a, b) => a-b);
console.log(arr); // [5, 4, 3, 2, 1]
console.log(sortedArr); // [1, 2, 3, 4, 5]
sort
会改变数组。但是比较函数将基于(+n, 0, -n)的返回值而不是布尔值来工作。请更改比较器。 - Kamrul