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

后端 未结 1 1021
萌比男神i
萌比男神i 2020-12-03 15:18

I have the following code:

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


        
1条回答
  •  抹茶落季
    2020-12-03 16:03

    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.

    0 讨论(0)
提交回复
热议问题