首页 > 解决方案 > Javascript console.log & dataflow

问题描述

I am trying to understand why under the first console.log(dates) it is showing that the dates are already sorted in ascending order before I call the sorting algorithm. Shouldn't the first console.log(dates) be showing me exactly what I have declared?

function doSomething()
{
    var dates = [
        {"date": 27, "month": 7},
        {"date": 26, "month": 7},
        {"date": 25, "month": 7},
        {"date": 24, "month": 7},
        {"date": 23, "month": 7}
    ];
    
    console.log(dates); //THIS PART SHOULD BE UNSORTED. WHY IS IT SORTED
    
       //sorting algorithm
       function sortArray(array, property, direction) 
       {
          direction = direction || 1;
          array.sort(function compare(a, b) 
          {
              let comparison = 0;
              if (a[property] > b[property]) 
              {
                  comparison = 1 * direction;
                  
              } else if (a[property] < b[property]) 
              {
                  comparison = -1 * direction;
    
              }
              return comparison;
          });
          return array; 
       }
        
       sortArray(dates, "date"); //Calling the sorting function
    
       console.log(dates); //HERE SHOULD BE SORTED
}

doSomething()

标签: javascripthtml

解决方案


似乎当console.log 达到对数组的读取访问权限时,它已经被排序,因为console.log 不是线程安全的。

它不会阻止执行流程继续对数组进行操作并对其进行排序。

如果我们调用执行阻塞函数(而不是 console.log ),它实际上会显示未排序的数组。

function LogTheDateMonthArray(arr){
  var str = "";
  for(var i=0;i<arr.length;i++){
    str += arr[i].date + ", " ;
  }
  document.getElementById('consoleLog').innerHTML=
    document.getElementById('consoleLog').innerHTML+"\n\n"+str;
}

这就是我在这个 codePen 中所做的:https ://codepen.io/xsimo/pen/JaoGoK


推荐阅读