如何在JavaScript中创建二维数组?

2021年4月9日16:48:45 发表评论 827 次浏览

二维数组是一个具有共同名称的项目的集合, 它们以行和列的形式组织成矩阵。二维数组是数组的数组, 因此我们创建一维数组对象的数组。

以下程序显示了如何创建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

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: