[英]How to create Javascript 2-d array like in PHP?
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. 我试图用java脚本形式复制2d数组生成我编写的以下PHP代码,我感觉我有一些误解,因为我没有从我的javascript获得预期的结果。 Help me out where I am doing it wrong and what is my misconception.
帮助我,我做错了什么,我的误解是什么。
PHP CODE PHP代码
<?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 JAVASCRIPT代码
<!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, 在@sifriday建议之后,我将数组初始化移到了内部循环之外,
Updated Question: But why do we have to initialize it everytime we need to expand the dimension unlike php 更新的问题:但是为什么我们每次需要扩展维度时都必须初始化它而不像php
Move your initialisation of the inner array outside the for loop, that should fix it. 将内部数组的初始化移到for循环之外,应该修复它。 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]);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.