Building a 2D Array in Javascript -


i've been trying build 2d array in javascript, not having success. i'm pulling data db , want combine fields 2d array in order use elsewhere in code. ideally want end is:

maplocs = [     ['name a','location a',1],     ['name b','location b',2],     ['name c','location c',3] ] 

here code using build maplocs array:

    for(i = 0;i < phtlen;i++){         var x = + 1;         var mylocs = new array(myphotogs[i].phtname,myphotogs[i].phtloc,x);         console.log(mylocs);         maplocs[i] = new array(mylocs);         }     } 

which pretty method i've gathered reading similar problems here. console.log() outputs array consisting of 3 elements want, if try access maplocs doesn't seem consist of 3 arrays have expected, of 3 elements each of made of 3 elements in myloc array if makes sense? so:

console.log(maplocs[0][0]); // joe bloggs, sw1a 1aa, 1 

where expecting 'joe bloggs' ,

console.logs(maplocs[0][1]); // undefined 

what doing wrong?

the explicit new array() constructor not take array , make new array identical argument array, takes list of arguments wish contained within new array. in line

maplocs[i] = new array(mylocs) 

maplocs[i] being set

[[joe bloggs, sw1a 1aa, 1]] 

instead, say

maplocs[i] = mylocs.slice() 

which clone mylocs , place @ index in maplocs, resulting in output want.


Comments