二维数组是一个具有共同名称的项目的集合, 它们以行和列的形式组织成矩阵。二维数组是数组的数组, 因此我们创建一维数组对象的数组。
以下程序显示了如何创建2D数组:
示例1:
<script>
//Create one dimensional array
var gfg = new Array(2);
document.write( "Creating 2D array <br>" );
//Loop to create 2D array using 1D array
for ( var i = 0; i <gfg.length; i++) {
gfg[i] = new Array(2);
}
var h = 0;
//Loop to initilize 2D array elements.
for ( var i = 0; i <2; i++) {
for ( var j = 0; j <2; j++) {
gfg[i][j] = h++;
}
}
//Loop to display the elements of 2D array.
for ( var i = 0; i <2; i++) {
for ( var j = 0; j <2; j++) {
document.write(gfg[i][j] + " " );
}
document.write( "<br>" );
}
</script>
输出如下:
Creating 2D array
0 1
2 3
示例2:
<script>
//Create one dimensional array
var gfg = new Array(3);
//Loop to create 2D array using 1D array
document.write( "Creating 2D array <br>" );
for ( var i = 0; i <gfg.length; i++) {
gfg[i] = [];
}
var h = 0;
var s = "lsbin" ;
//Loop to initilize 2D array elements.
for ( var i = 0; i <3; i++) {
for ( var j = 0; j <3; j++) {
gfg[i][j] = s[h++];
}
}
//Loop to display the elements of 2D array.
for ( var i = 0; i <3; i++) {
for ( var j = 0; j <3; j++)
{
document.write(gfg[i][j] + " " );
}
document.write( "<br>" );
}
</script>
输出如下:
Creating 2D array
G e e
k s f
o r G