I'm trying to push to a two-dimensional array without it messing up, currently My array is:
var myArray = [ [1,1,1,1,1], [1,1,1,1,1], [1,1,1,1,1] ]
And my code I'm trying is:
var r = 3; //start from rows 3 var c = 5; //start from col 5 var rows = 8; var cols = 7; for (var i = r; i < rows; i++) { for (var j = c; j < cols; j++) { myArray[i][j].push(0); } }
That should result in the following:
var myArray = [ [1,1,1,1,1,0,0], [1,1,1,1,1,0,0], [1,1,1,1,1,0,0], [0,0,0,0,0,0,0], [0,0,0,0,0,0,0], [0,0,0,0,0,0,0], ]
But it doesn't and not sure whether this is the correct way to do it or not.
So the question is how would I accomplish this?
Use myArray[i]. push( 0 ); to add a new column. Your code ( myArray[i][j]. push(0); ) would work in a 3-dimensional array as it tries to add another element to an array at position [i][j] .
push() method is used to push one or more values into the array. This method changes the length of the array by the number of elements added to the array. Parameters This method contains as many numbers of parameters as the number of elements to be inserted into the array.
JavaScript Array push() The push() method adds new items to the end of an array. The push() method changes the length of the array.
To push an object into an array, call the push() method, passing it the object as a parameter. For example, arr. push({name: 'Tom'}) pushes the object into the array. The push method adds one or more elements to the end of the array.
You have some errors in your code:
myArray[i].push( 0 );
to add a new column. Your code (myArray[i][j].push(0);
) would work in a 3-dimensional array as it tries to add another element to an array at position [i][j]
.One correct, although kind of verbose version, would be the following:
var r = 3; //start from rows 3 var rows = 8; var cols = 7; // expand to have the correct amount or rows for( var i=r; i<rows; i++ ) { myArray.push( [] ); } // expand all rows to have the correct amount of cols for (var i = 0; i < rows; i++) { for (var j = myArray[i].length; j < cols; j++) { myArray[i].push(0); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With