对日期数组/控制台错误进行排序?



我很困惑为什么控制台在两个日志上都向我显示一个排序数组。因为在我记录的第一个点不应该对其进行排序?

static reloadAndSortItems() {
let array = [];
const items = Store.getStoredItems();
items.forEach(function (item) {
// getting the stored date --> back to date object
let episodeDate = Date.parse(item.episode);
let parsedEpisode = new Date(episodeDate);

array.push(parsedEpisode);

});
**// should not sorted at this point
console.log('not sorted', array);**

let tested = array.sort(function (a, b) {
return a - b
});
**// should be sorted array at this point
console.log('sorted', tested);**


}

这是进来的数组(顺序不对

(:
["2018-09-13T00:30:00.000Z","2018-09-14T05:25:00.000Z","2018-09-13T00:30:00.000Z","2018-09-11T01:30:00.000Z","2018-09-11T01:30:00.000Z"]

这是因为sort()方法会改变初始数组,并且还会返回一个新数组,因此最终您将获得两个元素顺序相同的数组:

let arr = [1, 6, 2, 9, 3, 7];
let result = arr.sort((a, b) => a - b);
console.log('Original:', arr);
console.log('Final:', result);

为了避免这种行为,您可以创建其他数组(例如,使用map()方法,它返回一个新数组并且不会改变原始数组(,并将其用作初始数组:

let arr = [1, 6, 2, 9, 3, 7];
let duplicate = arr.map(d => d);
arr.sort((a, b) => a - b);
console.log('Sorted:', arr);
console.log('Duplicate of the initial array:', duplicate);

sort()方法会改变调用它的数组,因此此处要做的正确做法是记录以控制台array变量,而不是tested变量:

static reloadAndSortItems() {
let array = [];
const items = Store.getStoredItems();
items.forEach(function (item) {
// getting the stored date --> back to date object
let episodeDate = Date.parse(item.episode);
let parsedEpisode = new Date(episodeDate);    
array.push(parsedEpisode);    
});
array.sort(function (a, b) {
return a - b
});
console.log('sorted', array);    
}

或者,您可以通过.map()克隆array变量,然后在该克隆数组上调用.sort()方法,如下所示:

static reloadAndSortItems() {
let array = [];
const items = Store.getStoredItems();
items.forEach(function (item) {
// getting the stored date --> back to date object
let episodeDate = Date.parse(item.episode);
let parsedEpisode = new Date(episodeDate);    
array.push(parsedEpisode);    
});
// Copy/clone the array using map into tested variable
const tested = array.map(function(item) { return item; });
// Sort the tested array. Calling sort on tested will leave array unaffected
tested.sort(function (a, b) {
return a - b
});
console.log('sorted', tested);  // Sorted
console.log('array', array);    // Unsorted
}

最新更新