简体   繁体   中英

javascript executed in the wrong order

In Chrome console, it seems the 2nd line executes before the 1st line. Why?

function fn(obj){
    console.log(obj);
    obj.a = 1;
}

fn({b:1}); // prints {a:1, b:1} in console! WHAT!!!
fn({});    // prints {}. OMG. WHAT. This is inconsistent with above behaviour!

This DOESN'T happen in Edge console.

You are logging the object to console. Whatever you've logged is a reference to the actual object. Since you updated the object, the reference will reflect the latest value.

To test, you can try to log obj.a before setting it's value.

It seems to be a bug feature of the Chrome devtools console. For example if you run this code snippet, you will get

{
  "b": 1
}

But if at the same time you open the Chrome console, you will get something like this:

{b: 1}
  a:1
  b:1

As you can see, the first line reflects the obj state at the moment it was logged, but it's content seems to be updated when you click on it.

There is also a blue info tooltip to the right of the logged object that says: "Value below was evaluated just now", wich confirms that it is a feature, not a bug.

 function fn(obj){ console.log(obj); obj.a = 1; } fn({b:1}); 

that is because when you check the

{b:1}

the function already finished.

if you check the obj before the function finished,you will find out;for example:

在此输入图像描述

在此输入图像描述

在此输入图像描述

the obj at the console,when act like {...:...,...:...}

在此输入图像描述

it is a reference,

when you have checked it ,it show you a snapshot of the obj at that moment.At this time ,the obj always like {

...:...

...:...

}

for example:

在此输入图像描述

actually ,this is the real obj at that moment.

so,when you got time to check the obj ,the function already finished.So,you don't have chance to check the obj at that moment except :

在此输入图像描述

JSON.parse(JSON.stringify(obj)); 

give you another obj to see what happened at that moment.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM