运行时环境
- Visual Studio Code v1.15.1 自己的编译器
- Node.js v8.2.1
- 操作系统:Windows 10
描述
我想在 source arry 和 sort arry 之间添加“After sort:”,如下所示:
但控制台偶尔会显示:
为什么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/