gpt4 book ai didi

javascript - forEach 返回未定义

转载 作者:行者123 更新时间:2023-11-28 11:43:16 24 4
gpt4 key购买 nike

我希望 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com