Error in console.log?

Possible duplicate:
Is the Chrome JavaScript console lazy about evaluating arrays?

I am trying the following code:

var myList = new Object();
var item   = new Object();
item.text  = "item-1";
myList[3]  = item;

console.log(myList);
console.log(myList[3].text);

// Assign another object to the same entry
var item2   = new Object();
item2.text  = "item-2";
myList[3]  = item2;

console.log(myList);
console.log(myList[3].text);

The result is pretty odd:

* Object
  * 3: Object
      text: "item-2"

item-1

* Object
  * 3: Object
      text: "item-2"

item-2

BUT - if I execute the second part after a while (using setTimeout) and expand the first object, I get it right, that is:

* Object
  * 3: Object
      text: "item-1"

item-1

* Object
  * 3: Object
      text: "item-2"

item-2

It is very important for me to share it, since I think that you can spend a lot of time trying to understand what is wrong in its code. And if someone has a link to an open error or something else - answer this ticket. Thank!

+5
source share
5 answers

, "", , , , - , . " " .., , "LOG" ( ).

:

var person = {'name':'Tom'};
console.log( person);  //output the entire object variable
person.name = 'Thomas';
//the output is an object, whose 'name' value is 'Thomas', even though the log statement was placed before the value was changed to 'Thomas'.

:

var person = {'name':'Tom'};
console.log( person.name);    //changed to output a string variable
person.name = 'Thomas';
//the output here, however, has not dynamically updated and correctly outputs 'Tom'
+5

(50316), , , :

, theres , / . , console.log().

+3

, - . console.log(), , , , , . , setTimeout(), . console.log(), .

0

/ .

-, . , , , .

, - , , .

, ( Javascript ), , , .

0

I conducted several experiments with this "problem" in the latest version of Chrome 20.0.1132.57 m. To summarize the key points: -

  • console.log () prints an object reference using "> Object" when executing code
  • The state of the object is displayed when you click on the triangle, regardless of the line of code where console.log () is executed
  • If you want to print an object in its current state, print a clone console.log(JSON.parse(JSON.stringify(obj)));

You can use this bit of code to verify this in your own browser:

window.onload = function() {chto = {a : 10, b : 20};
console.log('Open this object after 5 seconds')
console.log(chto);
console.log('Open this object before 5 seconds')
console.log(chto);
console.log('Console of the cloned object')
console.log(JSON.parse(JSON.stringify(chto)));
setTimeout(function(){ console.log('5 seconds up'); chto['b'] = 30; },5000 ) ; };
0
source

All Articles