如何单次遍历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
相关产品推荐
相关产品推荐

