You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何单次遍历JavaScript多维数组并按位置提取数据?

遍历多维数组并按指定格式输出

给定如下多维数组:

var myArray = [
  ["id1", "john", 30],
  ["id2", "smith", 60],    
  ["id3", "kate", 90],
];

需要遍历数组,按位置获取数据,输出格式如下:

john is 30 
smith is 60 
kate is 90

实现方法

1. 普通for循环

最基础的遍历方式,通过索引逐个访问子数组:

for (var i = 0; i < myArray.length; i++) {
  // 子数组索引1对应名字,索引2对应年龄
  console.log(myArray[i][1] + " is " + myArray[i][2]);
}

2. forEach方法

用数组内置的forEach方法,写法更简洁:

myArray.forEach(function(item) {
  console.log(item[1] + " is " + item[2]);
});

3. for...of循环(ES6+)

ES6新增的迭代语法,逻辑更直观:

for (const item of myArray) {
  console.log(`${item[1]} is ${item[2]}`);
}

注:如果原数组里的id1、id2是未定义变量,记得给它们赋值或者改成字符串(比如"id1"),避免运行报错。

内容的提问来源于stack exchange,提问作者sinus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 09:45:29