且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

console.log() 显示值实际更改之前变量的更改值

更新时间:2022-06-14 23:34:34

Pointy's answer 有很好的信息,但不是这个问题的正确答案.

Pointy's answer has good information, but it's not the correct answer for this question.

OP 描述的行为是 2010 年 3 月首次报告的错误的一部分,该错误于 2012 年 8 月针对 Webkit 进行了修补,但截至撰写本文时尚未集成到 Google Chrome 中.该行为取决于在将对象文字传递给 console.log() 时控制台调试窗口是打开还是关闭.

The behavior described by the OP is part of a bug that was first reported in March 2010, patched for Webkit in August 2012, but as of this writing is not yet integrated into Google Chrome. The behavior hinges upon whether or not the console debug window is open or closed at the time the object literal is passed to console.log().

原始错误报告摘录(https://bugs.webkit.org/show_bug.cgi?id=35801):

Excerpts from the original bug report (https://bugs.webkit.org/show_bug.cgi?id=35801):

描述来自米奇克莱默 2010-03-05 11:37:45 PST

Description From mitch kramer 2010-03-05 11:37:45 PST

1) 创建一个具有一个或多个属性的对象字面量

1) create an object literal with one or more properties

2) console.log 该对象但保持关闭(不要在控制台中展开它)

2) console.log that object but leave it closed (don't expand it in the console)

3) 将其中一个属性更改为新值

3) change one of the properties to a new value

现在打开那个 console.log,你会看到由于某种原因它有新的值,即使它的值在它生成时是不同的.

now open that console.log and you'll see it has the new value for some reason, even though it's value was different at the time it was generated.

我应该指出,如果您打开它,如果不清楚,它将保留正确的值.

I should point out that if you open it, it will retain the correct value if that wasn't clear.

来自 Chromium 开发者的回复:

Response from a Chromium developer:

来自 Pavel Feldman 的评论 #2 2010-03-09 06:33:36 PST

Comment #2 From Pavel Feldman 2010-03-09 06:33:36 PST

我认为我们永远不会解决这个问题.我们不能在将对象转储到控制台时克隆它,也不能监听对象属性的变化以使其始终真实.

I don't think we are ever going to fix this one. We can't clone object upon dumping it into the console and we also can't listen to the object properties' changes in order to make it always actual.

我们应该确保现有的行为是预期的.

We should make sure existing behavior is expected though.

随之而来的是很多抱怨,最终导致错误修复.

Much complaining ensued and eventually it led to a bug fix.

来自 2012 年 8 月实施的补丁的变更日志说明 (http://trac.webkit.org/changeset/125174):

Changelog notes from the patch implemented in August 2012 (http://trac.webkit.org/changeset/125174):

截至今天,将对象(数组)转储到控制台将导致对象的属性被在控制台对象扩展时读取(即懒惰).这意味着在转储相同的对象时使用控制台进行调试将很难进行变异.

As of today, dumping an object (array) into console will result in objects' properties being read upon console object expansion (i.e. lazily). This means that dumping the same object while mutating it will be hard to debug using the console.

此更改开始为对象/数组生成缩略预览记录并将此信息传递到前端.这只发生在前端已打开,它仅适用于 console.log(),不适用于实时控制台交互.

This change starts generating abbreviated previews for objects / arrays at the moment of their logging and passes this information along into the front-end. This only happens when the front-end is already opened, it only works for console.log(), not live console interaction.