Why for-of-loop has not finished running, jump out to run console.log?

307 views Asked by At

Runtime environment

  • Visual Studio Code v1.15.1 own compiler
  • Node.js v8.2.1
  • OS: Windows 10

Description

I want to add "After sort:" between source arry and sort arry, look like this: CONSOLE Screenshot 1

But console occasionally shows: CONSOLE Screenshot 2

Why for-of-loop has not finished running, jump out to run console.log ? Source code:

// 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);
}
1

There are 1 answers

11
Raja Mohamed On

Seems array is not prepared when you try to print due to accessing same method from array property multiple times and the method contains some numerical calculation so surround by timeout

// 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);