Seytom Seytom - 18 days ago 7
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.

push([val1,val2]
), explicitly creating a new Array, then pushing the new Array. Here's the key part of the code:

var coordinates=[];
...
for(i=0;i<6;i++)
{
...
for(var j=start;j<circum[i].length;j++)
{
var segmentCoords=[];
...
if(segmentFlag===false)
{
segmentCoords.push([i+1,segmentLength]);
segmentFlag=true;
}
...
if(segmentFlag===true)
{
var tempArray=new Array(i+1,segmentLength);
segmentCoords.push(tempArray);
segmentLength+=sectorLength;
coordinates.push(segmentCoords);
segmentFlag===false;
}
...
}


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
[val1,val2,val3,val4,val5,val6]
. That is what I would expect if I were using
.concat()
or
.apply()
.

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

I've got the full code here https://jsfiddle.net/Seytom/7xm9s4qr/ in case you want to see more of it.

Answer

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

Comments