javascript console.log(array) 显示与迭代数组和显示单个元素不同的数组内容

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16484838/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 04:53:13  来源:igfitidea点击:

console.log(array) shows different array contents than iterating the array and displaying the individual elements

javascriptfirefox

提问by user1302914

I have the following code:

我有以下代码:

console.log("start");
for(var i = 0; i < array.length; i++){
    console.log(i + " = " + array[i]);
}
console.log(array);
console.log("end");

This gives me the following output:

这给了我以下输出:

[16:34:41.171] start
[16:34:41.171] 0 = 0
[16:34:41.172] 1 = 168
[16:34:41.172] 2 = 171
[16:34:41.172] [0, 168, 171, 139]
[16:34:41.172] end

That is, it doesn't show the 139 element when iterating the array, but console.log does print it when outputting the whole array. WHY? (<-- the question)

也就是说,它在迭代数组时不显示 139 元素,但在输出整个数组时 console.log 会打印它。为什么?(<-- 问题)

I do modify the array later on, is the console.log somehow delayed until after I changed the array? Note tho that change the order of the statements, and putting consoel.log(array)directly at the start does not change the outcome (still different outputs).

我稍后会修改数组,console.log 是否以某种方式延迟到我更改数组之后?请注意,更改语句的顺序,consoel.log(array)直接放在开头不会改变结果(仍然是不同的输出)。

I am using firefox 20.0

我正在使用 Firefox 20.0

回答by Daniel Aranda

Update:If you want to see this behavior, copy and paste the code in the console and execute. Then close developer tools and open again, apparently the pointer thing only happens when the code is executed in the background(which happens when you reopen the console).

更新:如果您想查看此行为,请将代码复制并粘贴到控制台中并执行。然后关闭开发人员工具并再次打开,显然只有在后台执行代码时才会发生指针的事情(当您重新打开控制台时会发生这种情况)。

Console.log output of objects, is a pointer, no a real value. This means that if the object changes later, console.log object will be updated. Try:

Console.log 输出的对象,是一个指针,没有一个真正的值。这意味着如果对象稍后更改,console.log 对象将被更新。尝试:

console.log("start");
var array = [1];
for(var i = 0; i < array.length; i++){
    console.log(i + " = " + array[i]);
}
console.log(array);
console.log("end");
array.push(9999);// you will see the 9999 in the console no matter it was added after the output.

To prevent pointer issues try this: console.log(array.join()); because later in some point of your application you are adding the 139 value.

为了防止指针问题,试试这个: console.log(array.join()); 因为稍后在您的应用程序的某个时刻,您将添加 139 值。