gpt4 book ai didi

javascript - 我怎样才能返回 foreach javascript 中的值

转载 作者:行者123 更新时间:2023-11-29 16:38:23 25 4
gpt4 key购买 nike

我有一个函数需要返回一个国家/地区的 ID。

我的列表是一个对象数组:

{
id: 2,
code: "AL",
name: "Albania"
}...

这是我从国家/地区获取所需 ID 的函数

getCountryID(countryName) {
return country_list_with_id.forEach(res => {
if (res.name.toLowerCase() === countryName) {
console.log("the id is",res.id)// the log is 143
let id = res.id;
return id;
}
});
}
console.log(array.getCountryID("USA"))//undefined

那么我怎样才能得到id呢?

最佳答案

你不能。 forEach 并不打算返回任何内容,但您可以使用另一个函数从数组中获取 id

使用find将返回一个满足您条件的对象。

getCountry(countryName) {
return country_list_with_id.find(item => item.name.toLowerCase() === countryName);
}

这将返回country对象,您可以从该对象注入(inject)ID。如果没有找到任何内容,则返回undefined。因此,您需要首先检查该对象,然后尝试访问其属性。

const country = array.getCountry("USA");

console.log(country && country.id);

关于javascript - 我怎样才能返回 foreach javascript 中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49191974/

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