【如何在JavaScript中创建二维数组()】二维数组是一个具有共同名称的项目的集合, 它们以行和列的形式组织成矩阵。二维数组是数组的数组, 因此我们创建一维数组对象的数组。
以下程序显示了如何创建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
推荐阅读
- Python使用Pandas处理日期和时间
- 进展问题(AP,GP,HP)详细介绍
- CSS边框属性用法示例
- 亚马逊面试题分享|S54(实习)
- 安装系统 华硕笔记本重装系统,教您华硕笔记本如何重装系统(安装系统)
- 读卡器怎样用,教您如何运用读卡器
- 0xc000000f,教您出错代码0xc000000f怎样修好
- bios中英文对比表,教您BIOS中英文对比表
- 如何进入bios设置,教您惠普如何进入bios设置u盘打开