Javascript 排序日期数组/控制台错误?
我不明白为什么控制台会在两个日志中显示一个排序数组。因为在我记录的第一个点,它不应该被排序Javascript 排序日期数组/控制台错误?,javascript,arrays,sorting,Javascript,Arrays,Sorting,我不明白为什么控制台会在两个日志中显示一个排序数组。因为在我记录的第一个点,它不应该被排序 static reloadAndSortItems() { let array = []; const items = Store.getStoredItems(); items.forEach(function (item) { // getting the stored date --> back to date object let e
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);**
}
这是即将进入的阵列(该阵列出现故障):
,因此在这里正确的做法是登录到控制台数组
变量,而不是测试的
变量:
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()
克隆数组
变量,然后在克隆的数组上调用.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
}
这是因为该方法会对初始数组进行变异,并返回一个新数组,所以最终将得到两个元素顺序相同的数组:
让arr=[1,6,2,9,3,7];
让结果=arr.sort((a,b)=>a-b);
console.log('Original:',arr);
console.log('Final:',result)代码>
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
}