I am trying to replicate the 2d array generation in java-script form the following PHP code I have written, I am feeling I am getting some misconception because I am not getting the expected result from my javascript. Help me out where I am doing it wrong and what is my misconception.
PHP CODE
<?php
$checkArray = array();
for($m=0; $m<3; $m++){
for($n=0; $n<4; $n++ )
{
$checkArray[$m][$n] = "Inside_ ".$m." is ".$n;
}
}
var_dump($checkArray);
?>
JAVASCRIPT CODE
<!DOCTYPE html>
<html lang="en">
<head>
<script>
function ArrayFunction(){
var checkArray = [];
for(var m=0; m<3; m++){
checkArray[m] = [];
for(var n=0; n<4; n++){
checkArray[m][n] = "Inside " +m+ " is " + n ;
}
}
for(var i = 0; i < checkArray.length; i++)
console.log(checkArray[i]);
}
</script>
</head>
<body>
The content of the document......
<input id="clickMe" type="button" value="clickme" onclick="ArrayFunction();" />
</body>
</html>
After @sifriday suggestion, I moved the array initialization outside inner loop,
Updated Question: But why do we have to initialize it everytime we need to expand the dimension unlike php
1 Answer 1
Move your initialisation of the inner array outside the for loop, that should fix it. Otherwise you're resetting it every time. Like this:
function ArrayFunction(){
var checkArray = [];
for(var m=0; m<3; m++){
// Move this to here!
checkArray[m] = [];
for(var n=0; n<4; n++){
checkArray[m][n] = "Inside " +m+ " is " + n ;
}
}
for(var i = 0; i < checkArray.length; i++)
console.log(checkArray[i]);
}
4 Comments
checkArray[m] like so: checkArray[m].push( "Inside " +m+ " is " + n);checkArray[m][n] then initially the value of checkArray[m] is undefined so this code will fail. So first you need to define it checkArray[m] = [] and only then can you do checkArray[m][n]