JavaScript 中创建二维数组的方法有:直接创建二维数组(使用数组字面量语法)使用 Array.from() 方法从一维数组创建使用 for 循环和 push() 方法手动创建

JavaScript 中如何创建二维数组
直接创建
最简单的创建二维数组的方法是使用数组字面量语法:
<code class="javascript">const myArray = [ [1, 2, 3], [4, 5, 6], [7, 8, 9], ];</code>
使用 Array.from()
要从一维数组创建二维数组,可以使用 Array.from() 方法:
<code class="javascript">const myArray = Array.from(Array(3), () => new Array(3));</code>
生成的数组将包含三个内层数组,每个内层数组包含三个元素。
本文档主要讲述的是Sencha touch 开发指南;主要介绍如何使用Sencha Touch为手持设备进行应用开发,主要是针对iPhone这样的高端手机,我们会通过一个详细的例子来介绍整个开发的流程。 Sencha Touch是专门为移动设备开发应用的Javascrt框架。通过Sencha Touch你可以创建非常像native app的web app,用户界面组件和数据管理全部基于HTML5和CSS3的web标准,全面兼容Android和Apple iOS。希望本文档会给有需要的朋友带来帮助;感兴趣的
0
使用 for 循环
还可以使用 for 循环和 push() 方法手动创建二维数组:
<code class="javascript">const myArray = [];
for (let i = 0; i < 3; i++) {
myArray[i] = [];
for (let j = 0; j < 3; j++) {
myArray[i].push(i * 3 + j);
}
}</code>示例
使用上述方法创建的二维数组示例:
<code class="javascript">// 使用数组字面量语法
const myArray1 = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
];
// 使用 Array.from()
const myArray2 = Array.from(Array(3), () => new Array(3));
// 使用 for 循环
const myArray3 = [];
for (let i = 0; i < 3; i++) {
myArray3[i] = [];
for (let j = 0; j < 3; j++) {
myArray3[i].push(i * 3 + j);
}
}
console.log(myArray1); // 输出:[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
console.log(myArray2); // 输出:[[], [], []]
console.log(myArray3); // 输出:[[0, 1, 2], [3, 4, 5], [6, 7, 8]]</code>以上就是js如何创建二维数组的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号