JS遍历含嵌套数组的对象数组报[object Object] undefined如何解决
问题说明
遍历包含数组的对象数组,格式化输出汽车品牌及对应车型数据时,代码运行返回[object Object] undefined错误,无法得到预期结果。
预期输出格式
Saab - Smodel1,Smodel2,Smodel3, Volvo - Vmodel1,Vmodel2,Vmodel3, BMW - Bmodel1,Bmodel2,Bmodel3,
原错误代码
const cars = [{ "Saab":["Smodel1", "Smodel2", "Smodel3"], "Volvo":["Vmodel1", "Vmodel2", "Vmodel3"], "BMW":["Bmodel1", "Bmodel2", "Bmodel3"] }]; let car_model = ''; for(let i = 0; i < cars.length; i++) { car_model += cars[i] + "-" + cars[i][i] + "<br/>"; }
补充的参考代码存在语法错误、未定义变量问题,无法直接运行:
var cars = var car, hash; for (var model in cars) { car = key; hash = cars[key]; get(car, hash); seen(car, hash); (function loop(car, hash) { setTimeout(function () { get(car, hash); loop(car, hash); }, 1000); })(car, hash); }
错误原因
cars是长度为1的数组,唯一元素为存储全量品牌车型数据的普通对象,直接拼接对象时,JS会自动将对象转为字符串[object Object]- 原代码用数字索引
i读取对象属性,而对象的键是字符串类型的品牌名,不存在数字索引对应的属性,因此取到undefined - 补充参考代码存在变量未赋值、未定义变量(
key/get/seen均未声明实现)、语法不完整问题,无实际运行价值
修正后实现代码
const cars = [{ "Saab":["Smodel1", "Smodel2", "Smodel3"], "Volvo":["Vmodel1", "Vmodel2", "Vmodel3"], "BMW":["Bmodel1", "Bmodel2", "Bmodel3"] }]; let car_model = ''; for(let i = 0; i < cars.length; i++) { const brandData = cars[i]; // 遍历当前数据对象的所有品牌键 for (const brandName in brandData) { // 用逗号拼接车型数组,按格式拼接字符串 car_model += `${brandName} - ${brandData[brandName].join(',')},<br/>`; } } // 输出拼接完成的结果 document.write(car_model);
运行上述代码即可得到符合预期的格式化输出。
内容的提问来源于stack exchange,提问作者saint thomas
相关产品推荐
相关产品推荐

