javascript - 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()
解决方案
似乎当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
推荐阅读
- reactjs - 警告:道具类型失败:提供给“MenuItem”的道具“子项”无效,应为 ReactNode
- excel - XlFileFormat 57 是否仍然有效将 Excel 工作表另存为 PDF?
- apple-music - Apple Music API 中有多少个排行榜位置可用?
- json - 描述 JSON 结构的原型,该结构具有两种可能类型的项目列表
- c++ - 为什么我在“push_back”对向量的第二个元素中出现 C3867 错误?
- javascript - React re-rendering components twice?
- c# - C# 如何使用 HTTP URI 获取 o365 附件
- java - 如何通过 optaplanner 引擎获得没有任何硬分的解决方案
- c++ - 在数组中查找元素,找到则返回找到,否则返回未找到
- c++ - 将函数指针作为函数参数传递的目的