为什么 for-of 遍历还未执行完却跳出去执行 console.log() ?

1.问题描述:

遇到一个关于 console.log() 和 for-of 遍历的问题,我的本意是想在排序数组和未排序数组的中间加上“排序后:”,但是在实际执行打印的时候,这个 "排序后:" 偶尔会跑到未排序的原始数组中间去。

  • 出错时的显示:
    出错的显示

  • 正确时的显示:
    正确的显示

Q: 为什么偶尔会发生 for-of 内部循环未执行完,却跳出去执行全局的 console.log() 的情况呢?

2.编程工具:

VScode v1.15.1 自带的编译器 Node.js v8.2.1

3.代码如下:

// 随机生成随机两位数
function getRandom() {
  return Math.round(Math.random() * 100);
}

// 将分数写入数组
var score = [
  ["小明", getRandom()],
  ["小二", getRandom()],
  ["张三", getRandom()],
  ["李四", getRandom()],
  ["老王", getRandom()]
];

// 遍历打印原始数组
for (let m of score) {
  console.log(m);
}

// 调用 sort() 函数对数组进行排序
score.sort((a, b) => {
  return b[1] - a[1];
});

// 排序后分割标记
console.log("排序后:");

// 遍历打印排序后的数组
for (let n of score) {
  console.log(n);
}
阅读 3.2k
2 个回答

我试了好多次都没有你说的情况出现,按理说也不应该出现这种情况,难道是运行for循环的时候陷入了阻塞?就先执行下面的了?我在你的代码上做了一个小改动,保证不会发生这样的情况.

// 随机生成随机两位数
  function getRandom() {
    return Math.round(Math.random() * 100);
  }
  // 将分数写入数组
  var score = [
    ["小明", getRandom()],
    ["小二", getRandom()],
    ["张三", getRandom()],
    ["李四", getRandom()],
    ["老王", getRandom()]
  ];

  // 遍历打印原始数组
  for (let m of score) {
    console.log(m);
  }
  // 调用 sort() 函数对数组进行排序
  score.sort((a, b) => {
    return b[1] - a[1];
  })

  //定义一个flag
  var flag = true
  // 遍历打印排序后的数组
  for (let n of score) {
    if(flag) {
      console.log('排序后')
      flag = false
    }
    console.log(n);
  }

不存在你说的问题啊

// 随机生成随机两位数
function getRandom() {
  return Math.round(Math.random() * 100);
}

// 将分数写入数组
var score = [
  ["小明", getRandom()],
  ["小二", getRandom()],
  ["张三", getRandom()],
  ["李四", getRandom()],
  ["老王", getRandom()]
];

// 遍历打印原始数组
for (let m of score) {
  console.log(m);
}

// 调用 sort() 函数对数组进行排序
score.sort((a, b) => {
  return b[1] - a[1];
});

// 排序后分割标记
console.log("排序后:");

// 遍历打印排序后的数组
for (let n of score) {
  console.log(n);
}

VM4831:17 (2) ["小明", 22]
VM4831:17 (2) ["小二", 68]
VM4831:17 (2) ["张三", 76]
VM4831:17 (2) ["李四", 25]
VM4831:17 (2) ["老王", 67]
VM4831:26 排序后:
VM4831:30 (2) ["张三", 76]
VM4831:30 (2) ["小二", 68]
VM4831:30 (2) ["老王", 67]
VM4831:30 (2) ["李四", 25]
VM4831:30 (2) ["小明", 22]
undefined
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题