Push() with Arrays of Arrays in Javascript -


i trying build 'array of arrays' (think of table columns , rows). have code loops through each 'row', , builds array of 'columns' pushes onto array of rows:

var myrows = [];  // array of 'column' arrays var mycols = [];  // 'buffer' each column  (r=4; r>=0; r--) {    mycols.length = 0;    (c=0; c<10; c++) {    mycols.push("row: " + r +", col: " + c);   }   myrows.push(mycols); } console.log(myrows); 

what expect console.log(myrows) this:

[array[10], array[10], array[10], array[10], array[10]] 0: array[10] 0: "row: 0, col: 0" 1: "row: 0, col: 1" 2: "row: 0, col: 2" 3: "row: 0, col: 3" 4: "row: 0, col: 4" 5: "row: 0, col: 5" 6: "row: 0, col: 6" 7: "row: 0, col: 7" 8: "row: 0, col: 8" 9: "row: 0, col: 9" length: 10 __proto__: array[0] 1: array[10] 0: "row: 1, col: 0" 1: "row: 1, col: 1" 2: "row: 1, col: 2" 3: "row: 1, col: 3" 4: "row: 1, col: 4" 5: "row: 1, col: 5" 6: "row: 1, col: 6" 7: "row: 1, col: 7" 8: "row: 1, col: 8" 9: "row: 1, col: 9" length: 10 ... 

however, instead logged (in chrome) shows row being '0' each iteration. not that, if change iteration rules not go 0, shows whichever last 'row' sub arrays of 'myrows' set of arrays.

really scratching head @ one, there push() method i'm not understanding?

you need create new cols array each time through outer loop. you're using same cols array each row, , modifying in place, because myrows.push(mycols) pushes reference array, doesn't make copy.

change:

mycols.length = 0; 

to:

mycols = []; 

Comments

Popular posts from this blog

java - How to specify maven bin in eclipse maven plugin? -

single sign on - Logging into Plone site with credentials passed through HTTP -

php - Why does AJAX not process login form? -