console.log中的错误?

guy*_*oni 5 javascript console firefox google-chrome javascript-debugger

可能重复:
Chrome的JavaScript控制台是否懒于评估数组?

我尝试以下代码:

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);
Run Code Online (Sandbox Code Playgroud)

结果很奇怪:

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

item-1

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

item-2
Run Code Online (Sandbox Code Playgroud)

但是 - 如果我在一段时间后执行第二部分(使用setTimeout),并展开第一个对象,我说得对,即:

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

item-1

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

item-2
Run Code Online (Sandbox Code Playgroud)

我发现分享它很重要,因为我认为可以浪费大量时间来试图理解他的代码中的错误.如果有人提到一个开放的bug或其他东西 - 请回复此票.谢谢!

Tom*_*ell 5

我的观点是,这是一个令人讨厌的"特征",我真的希望我可以关闭它,它使调试成为一场噩梦,不知道在哪个时间点某些东西可能更新了一个对象,同时试图在一个对象上建立确切的对象状态.在代码中给出一点.该功能可用于"观察点"等,但不能用于称为"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'.
Run Code Online (Sandbox Code Playgroud)

然后:

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'
Run Code Online (Sandbox Code Playgroud)


phe*_*nal 0

在我看来,这更像是一种竞争条件。由于您仅传递对 的引用console.log(),因此它所引用的值在实际记录时可能已更改。然后,当您使用 setTimeout() 时,该值会在记录后发生变化。不传递对 的引用console.log(),而是传递该值的克隆。