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

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

问题描述

我有以下代码:

  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会打印它。为什么? (< - 问题)

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



我使用firefox 20.0

解决方案

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



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); //无论输出结果是否添加,您都将在控制台中看到9999。

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


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)

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

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

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

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