1

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

3

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]);
    }
Sign up to request clarification or add additional context in comments.

4 Comments

Adding onto this: it's also probably better to use Array.prototype.push to add items to checkArray[m] like so: checkArray[m].push( "Inside " +m+ " is " + n);
@sifriday Oh thanks !! that was the blunder I am doing :) .. Can you suggest me some good online source to study the JavaScript and best approach to follow.
@sifriday I updated the question as per your suggestion, with a bit new query.
Thanks nmarsh, +1. Stackup, the answer to your new query is simply that PHP's array handling is pretty good, and you get a lot of flexibility with both multidimensional arrays and associative arrays. In JavaScript the language requires you you go in two stages. If you tried to do it one and call 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]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.