Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

array splice and console.log [duplicate]

Tags:

javascript

When I perform operations on an array in javascript, console.log shows the array as having been already changed BEFORE I do an operation on the array. I can reproduce this in chrome and firefox. Anyone know why this is?

var myTabs = [[0,0,0],
              [0,0,0],
              [0,0,0],
              [0,0,0]];
console.log(myTabs);
myTabs[0].splice(1, 1);
console.log(myTabs);

See this for code:

https://jsfiddle.net/mxrh33t0/1/

like image 961
froopydoop Avatar asked Jan 29 '23 20:01

froopydoop


1 Answers

When you expand a logged object in Chrome, you are expanding the last reference to it, not a copy of that object at the moment that it was logged.

In your case, the last reference was to the array after the splice() method had been called. If you would like to verify the difference, you will have to be more specific with your logging:

var myTabs = [[0,0,0],
              [0,0,0],
              [0,0,0],
              [0,0,0]];
console.log(myTabs[0].join(","));
myTabs[0].splice(1, 1);
console.log(myTabs[0].join(","));

You can expand on that if you really want to see more.

like image 151
rmlan Avatar answered Feb 02 '23 00:02

rmlan