javascript - 为什么for-of-loop还没运行完,就跳出来运行console.log?

标签 javascript node.js visual-studio-code console.log node-inspector

运行时环境

  • Visual Studio Code v1.15.1 自己的编译器
  • Node.js v8.2.1
  • 操作系统:Windows 10

描述

我想在 source arry 和 sort arry 之间添加“After sort:”,如下所示: CONSOLE Screenshot 1

但控制台偶尔会显示: CONSOLE Screenshot 2

为什么for-of-loop还没有运行完,跳出运行console.log?源代码:

// Random to generate double digits.
function getRandom() {
  return Math.round(Math.random() * 100);
}
// Writing data to the array.
var score = [
  ["a", getRandom()],
  ["b", getRandom()],
  ["c", getRandom()],
  ["d", getRandom()],
  ["e", getRandom()]
];
console.log("Before sort:");

// Print source arry
for (let m of score) {
  console.log(m);
}

// Call sort()
score.sort((a, b) => {
  return b[1] - a[1];
});
console.log("After sort:");

// Print sort arry.
for (let n of score) {
  console.log(n);
}

最佳答案

由于多次从数组属性访问相同的方法,并且该方法包含一些数值计算,因此尝试打印时似乎数组未准备好,因此超时

// Random to generate double digits.
   function getRandom() {
     return Math.round(Math.random() * 100);
    }
   // Writing data to the array.
   var score = [
   ["a", getRandom()],
   ["b", getRandom()],
   ["c", getRandom()],
   ["d", getRandom()],
   ["e", getRandom()]
  ];
  console.log("Before sort:");
  setTimeout(function(){
      // Print source array
      for (let m in score) {
        console.log(m);
       }

      // Call sort()
     score.sort((a, b) => {
         return b[1] - a[1];
     });
     console.log("After sort:");
     for (let n in score) {
       console.log(n);
     }
  },300);

关于javascript - 为什么for-of-loop还没运行完,就跳出来运行console.log?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46040467/

相关文章:

visual-studio-code - 带有 VScode 的 phpcs - 如何禁用行长警告?

crtexe.c - 关于在 VSCode 中调试 C/C++ 文件的问题

javascript - 在异步函数中使用 While 循环?

javascript - 如何在单击其列表项时关闭侧边菜单?

javascript - Array.prototype.map(callback, thisArg),第二个参数被忽略

javascript - 使用新条目更改 div 的值并且不附加

javascript - discord.js 将消息作为代码块发送?

javascript - 如何使用 jquery 从 HTML 表中选择特定行?

javascript - 重置进度条值 jQuery

visual-studio-code - 有什么方法可以更改 VSCode 中仅注释代码的字体系列?