Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
238 views
in Technique[技术] by (71.8m points)

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...