Seytom Seytom - 3 months ago 19
Javascript Question

Javascript pushing Array to Array but concatenating instead

I'm trying to push an array (multiple times) into another array. Instead of an array of arrays, I'm getting all the values from the multiple push attempts as a single array. I've tried pushing an array implicitly (i.e.

), explicitly creating a new Array, then pushing the new Array. Here's the key part of the code:

var coordinates=[];
for(var j=start;j<circum[i].length;j++)
var segmentCoords=[];
var tempArray=new Array(i+1,segmentLength);

From the many stackoverflow questions/answers I've looked at, I expect my coordinates array to look something like this:
[[val1, val2],[val3,val4],[val5,val6]]
. Instead it's
. That is what I would expect if I were using

Can anyone explain why my code isn't generating an array of arrays?

I've got the full code here in case you want to see more of it.


You seem to be fooled by your console.log. Notice the difference between these two statements:

console.log('string ' + [[1,2],[3,4]]); // string, '1,2,3,4'

console.log('string ', [[1,2],[3,4]]); // string, [[1,2],[3,4]]

Because you are coercing the array into a string, this is the result. Its the same as:

document.write( new Array([1,2],[3,4]).join(',') ); // 1,2,3,4

It's simply what arrays do when you join them, regardless of whether they are nested. It is better to log the array separately so you can explore it in your console, so simple print your string and then add the array as the second argument. (The console takes an infinite amount of arguments and will print them all as one statement - safari even prints the first as a special type if its a string so its clearer to read).

In short: push behaves exactly as expected, and your code should simply work as intended, but the printing to the console seems to leave a bit to be desired :).