我希望 foreach() 循环遍历映射数组并检查类型值是否匹配。如果没有返回else语句。
函数
function checkCars(carData) {
const cars = carData.models;
models.forEach(model => {
if (model.type === 'Toyota' || model.type === 'Hyundai') {
return "Type A";
} else {
return "Type B";
}
});
}
数据库
"models": [
{type: "Toyota"}
{type: "Hyundai"}
{type: "Audi"}
{type: "VW"}
]
最佳答案
Array.prototype.forEach()的返回值是未定义
,您无法从forEach()
显式返回任何内容。
您可以尝试使用 Array.prototype.map()相反:
The
map()
method creates a new array populated with the results of calling a provided function on every element in the calling array.
function checkCars(carData) {
const cars = carData.models;
return models.map(model => {
if (model.type === 'Toyota' || model.type === 'Hyundai') {
return "Type A";
} else {
return "Type B";
}
});
}
关于javascript - forEach 返回未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59807380/