console.log(array) 显示与迭代数组和显示单个元素不同的数组内容 [英] console.log(array) shows different array contents than iterating the array and displaying the individual elements

查看:15
本文介绍了console.log(array) 显示与迭代数组和显示单个元素不同的数组内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

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

这给了我以下输出:

[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

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

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)

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

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).

我使用的是 Firefox 20.0

I am using firefox 20.0

推荐答案

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

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 输出的对象,是一个指针,没有真正的值.这意味着如果对象稍后更改,console.log 对象将被更新.试试:

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("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.

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

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) 显示与迭代数组和显示单个元素不同的数组内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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