How to explain this phenomenon in JS? What is the principle?

data obtains the data asynchronously, then saves it in the local variable after processing.
the first console shows a value
but the second cannot get the index
the third can get the index after 400 milliseconds. Why?

clipboard.png

clipboard.png

May.22,2021

The reason for this is actually that the data you see on the console will be changed by subsequent operations because the array is a reference type , so what you see on the console is not what it printed out at that time
you can try this code

const data = [];

setTimeout(() => {
  data.push({})
}, 100);

console.log('1', data);
console.log('2', JSON.stringify(data));
console.log('3', data[0]);

setTimeout(() => {
  console.log('4', data[0]);
}, 400);

whether it is correct to understand that 1 and 2 should be the same, but the reality is


Asynchronous didn't wait, right? 400 milliseconds when the asynchronous request ends


this.data and the this.data, in the timer point to the same?


my understanding is that it takes time to traverse data. When console, it does not traverse data [0], so it is undefined

.
Menu