提示一个字符串.在数组中标识它,如果是,则返回作为该字符串的事实编写的信息



我已经定义了一个数组。我想做的是确定用户给出的单词是否在我的数组中,如果是,则向用户返回数组中有关该单词(字符串)的信息

var countryNameArray = [{
  name: 'France',
  fact: 'they speak french'
}, {
  name: 'Belgium',
  fact: 'they speak french or dutch'
},];
if (countryNameArray.indexOf(WordGiven[countryNameArray])) {
  console.info(countryNameArray.includes(WordGiven));
  alert(countryNameArray.name, + + , countryNameArray.fact)
} else {
  alert ('I did not understand. Please give me a Country Name')
};

需要明确的是,您要问的是给定一个字符串,您希望在 countryNameArray 中获取该对象,其名称与给定字符串匹配。

实现这一点的一种方法是使用过滤器。

var countryNameArray = [
    {
        name: 'France',
        fact: 'they speak french'
    },
    {
        name: 'Belgium',
        fact: 'they speak french or dutch'
    },
];
var matchingCountries = countryNameArray.filter(c => c.name === WordGiven);

从过滤器中,您将拥有一个名称与 WordGiven 匹配的数组,您可以从中以任何您想要的方式进行处理,例如

if (matchingCountries.length === 0) {
    console.log('No matching country found');
} else {
    var firstMatch = matchingCountries.first();
    console.log(firstMatch.name, + + , firstMatch.fact);
}

编辑:在使用find看到另一个答案后,这更适合您要实现的目标。用过滤器代替查找,你不需要做整个.first()的东西。

您可以使用

.find()返回与用户输入匹配的name的对象。然后,您可以使用析构赋值从找到的对象中获取属性( javascript 对象的namefact)。

请参阅下面的工作示例:

const countryNameArray = [{
    name: 'France',
    fact: 'they speak french'
  },
  {
    name: 'Belgium',
    fact: 'they speak french or dutch'
  },
],
wordGiven = prompt("Enter a country name");
if(countryObj = countryNameArray.find(({name}) => name === wordGiven)) {
  const {name, fact} = countryObj; // get the name and fact properties from countryObj
  alert(name + ': ' + fact);
} else {
  alert('I did not understand. Please give me a Country Name');
}

通过创建一个函数并将国家/地区名称作为参数传递,我们可以使用 find() 方法实现这一点。

const countryNameArray = [{
    name: 'France',
    fact: 'they speak french'
},
{
    name: 'Belgium',
    fact: 'they speak french or dutch'
    },
];
const result = (name) => {
    let country = countryNameArray.find(obj => obj.name === name);
    if (country) {
        alert(`${country.name} ${country.fact}`); // 'France they speak french'
    } else {
        alert ('I did not understand. Please give me a Country Name')
    }
}
result('France');

最新更新