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

时间:2018-09-11 00:16:41

标签: javascript arrays sorting

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

["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"]

这是传入的数组(乱序):

var element = document.getElementById('element-to-print');
var opt = {
  margin:       0,
  filename:     'myfile.pdf',
  image:        { type: 'jpeg', quality: 0.98 },
  html2canvas:  { scale:1 },
  jsPDF:        { unit: 'in', format: 'letter', orientation: 'portrait' }
};
html2pdf(element).set(opt)

2 个答案:

答案 0 :(得分:1)

The sort() method mutates the array it's called on,所以这里要做的正确的事情是登录控制台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);    
  }

或者,您可以通过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
  }

答案 1 :(得分:1)

这是因为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);