我怎么能在 foreach JavaScript 中返回值



我有一个函数需要返回一个国家的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

那么我怎样才能获得身份证呢?

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

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

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

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

const country = array.getCountry("USA");
console.log(country && country.id);
您可以

filter国家/地区数组以获取所需的国家/地区,并返回结果。 countries[0]可能undefined因此请使用我示例中的 if 语句或@void示例中的三元运算符 这是代码片段:

const countries = [{ id: 2, code: "AL", name: "Albania" }, { id: 3, code: "DZ", name: "Algeria" }, { id: 4, code: "DS", name: "American Samoa" }];
function getCountryId(code) {
  const country = countries.filter(country => country.code === code);
  if(country.length > 0) {
    return country[0].name;
  } else {
    return "No such country.";
  }
}
console.log(getCountryId("DZ"));
console.log(getCountryId("USA"));

您可以使用

Array.prototype.filter按名称过滤出国家/地区,然后返回first/last项的id

const list = [{
  id: 2,
  code: "AL",
  name: "Albania"
}, {
  id: 3,
  code: "DZ",
  name: "Algeria"
}, {
  id: 4,
  code: "DS",
  name: "American Samoa"
}];
function getCountryId(name) {
  return (list.filter((country) => country.name === name)[0] || {}).id;
}
console.log(getCountryId('Algeria'));
console.log(getCountryId('NoneExistingCountry'));

使用需要在这里使用.filter。这将从与特定条件匹配的数组中返回项目

 var data = [{ id: 2, code: "AL", name: "Albania" }, { id: 3, code: "DZ", name: "Algeria" }, { id: 4, code: "DS", name: "American Samoa" }]
Array.prototype.getCountryID = function(code){
  var output = this.filter(el => el.code === code);
  return output.length > 0 ? output[0].id : "Not Found";
}
console.log(data.getCountryID("DS"));
console.log(data.getCountryID("something else"));

最新更新