Chrome 的 JavaScript 控制台是否懒得评估数组? [英] Is Chrome's JavaScript console lazy about evaluating arrays?

查看:25
本文介绍了Chrome 的 JavaScript 控制台是否懒得评估数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将从代码开始:

var s = ["hi"];
console.log(s);
s[0] = "bye";
console.log(s);

很简单吧?对此,Firebug 表示:

Simple, right? In response to this, Firebug says:

["hi"]
["bye"]

很棒,但 Chrome 的 JavaScript 控制台(7.0.517.41 测试版)说:

Wonderful, but Chrome's JavaScript console (7.0.517.41 beta) says:

["bye"]
["bye"]

是我做错了什么,还是 Chrome 的 JavaScript 控制台在评估我的数组时非常懒惰?

Have I done something wrong, or is Chrome's JavaScript console being exceptionally lazy about evaluating my array?

推荐答案

感谢您的评论,tec.我能够找到一个现有的未确认的 Webkit 错误来解释这个问题:https://bugs.webkit.org/show_bug.cgi?id=35801(现已修复!)

Thanks for the comment, tec. I was able to find an existing unconfirmed Webkit bug that explains this issue: https://bugs.webkit.org/show_bug.cgi?id=35801 ( now fixed!)

似乎有一些关于它有多少错误以及它是否可以修复的争论.在我看来,这确实是一种不良行为.这对我来说尤其令人不安,因为至少在 Chrome 中,当代码驻留在立即执行的脚本中时(在页面加载之前),即使在控制台打开时,只要刷新页面,就会发生这种情况.当控制台尚未激活时调用 console.log 只会导致对正在排队的对象的引用,而不是控制台将包含的输出.因此,在控制台准备好之前,不会评估数组(或任何对象).这确实是一个懒惰评估的案例.

There appears to be some debate regarding just how much of a bug it is and whether it's fixable. It does seem like bad behavior to me. It was especially troubling to me because, in Chrome at least, it occurs when the code resides in scripts that are executed immediately (before the page is loaded), even when the console is open, whenever the page is refreshed. Calling console.log when the console is not yet active only results in a reference to the object being queued, not the output the console will contain. Therefore, the array (or any object), will not be evaluated until the console is ready. It really is a case of lazy evaluation.

但是,有一种简单的方法可以在您的代码中避免这种情况:

However, there is a simple way to avoid this in your code:

var s = ["hi"];
console.log(s.toString());
s[0] = "bye";
console.log(s.toString());

通过调用 toString,您可以在内存中创建一个表示,该表示不会被以下语句更改,控制台将在准备好时读取该语句.控制台输出与直接传递对象略有不同,但似乎可以接受:

By calling toString, you create a representation in memory that will not be altered by following statements, which the console will read when it is ready. The console output is slightly different from passing the object directly, but it seems acceptable:

hi
bye

这篇关于Chrome 的 JavaScript 控制台是否懒得评估数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆