带有数组赋值的 JavaScript 意外控制台输出;
在 webkit 浏览器(Chrome 16.0.912.77 和 Safari 5.1.2 - 7534.52.7)中进行数组分配后,我收到意外的控制台输出。
这是我的函数,它演示了该错误:
function test() {
var myArray = [];
console.log(myArray); // Should be [], but is [0]
myArray.push(0);
}
我在 Firefox 7.0.1 中收到了 [] 的预期输出。
[编辑]
当我插入长时间同步睡眠时,问题不会消失。这让我认为(1)即使 console.log 语句是异步的,它也在同一个线程中运行,(2)它在运行之前等待直到事件队列为空,(3)传递给控制台的引用当 console.log 最终执行时,.log 被转换为字符串 - 而不是在调用它时。
function sleep(millis){
var date = new Date();
var curDate = null;
do { curDate = new Date(); }
while(curDate-date < millis);
}
function test() {
var myArray = [];
console.log(myArray); // Should be [], but is [0]
sleep(2000);
myArray.push(0);
}
这似乎不是理想的行为。
I am getting unexpected console output after array assignment in webkit browsers (Chrome 16.0.912.77 and Safari 5.1.2 - 7534.52.7).
Here is my function that demonstrates the error:
function test() {
var myArray = [];
console.log(myArray); // Should be [], but is [0]
myArray.push(0);
}
I receive the expected output of [] in Firefox 7.0.1.
[EDIT]
When I insert a long synchronous sleep, the problem doesn't go away. This makes me think that (1) even though the console.log statement is asynchronous, it is running in the same thread and (2) it is waiting until the event queue is empty before it runs and (3) the reference passed to console.log is being turned into a string when console.log is finally executed - not when it is called.
function sleep(millis){
var date = new Date();
var curDate = null;
do { curDate = new Date(); }
while(curDate-date < millis);
}
function test() {
var myArray = [];
console.log(myArray); // Should be [], but is [0]
sleep(2000);
myArray.push(0);
}
This doesn't seem like desired behavior.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是因为
console.log
是通过引用且异步的,并且您的push()
在显示结果之前最终执行。您可以快速执行:
相反,出于调试目的。
为了更明显地测试这一点:
将给出
[1,2,3,4,5]
。当 t = 5 时,给出错误的结果;当 t = 100 时,给出正确的结果。
This is because
console.log
is by reference and asynchronous, and yourpush()
ends up executing before the result is displayed.You could do a quick:
Instead, for debugging purposes.
To test this more obviously:
will give
[1, 2, 3, 4, 5]
.gives the wrong result for me with t = 5 and the right result for t = 100.