Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 提示一个字符串。在数组中标识它,如果是,则返回作为该字符串事实写入的信息_Javascript_Arrays_Node.js_String - Fatal编程技术网

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

Javascript 提示一个字符串。在数组中标识它,如果是,则返回作为该字符串事实写入的信息,javascript,arrays,node.js,string,Javascript,Arrays,Node.js,String,我已经定义了一个数组。我想做的是确定用户给出的单词是否在我的数组中,如果是,则向用户返回数组中关于该单词字符串的信息 var countryNameArray = [{ name: 'France', fact: 'they speak french' }, { name: 'Belgium', fact: 'they speak french or dutch' },]; if (countryNameArray.indexOf(WordGiven[countryNameAr

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

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')
};

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


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

实现这一目标的一种方法是使用

从filter中,您将拥有一个名称与WordGiven匹配的数组,例如,您可以用任何方式处理该数组

if (matchingCountries.length === 0) {
    console.log('No matching country found');
} else {
    var firstMatch = matchingCountries.first();
    console.log(firstMatch.name, + + , firstMatch.fact);
}
编辑:在看到另一个答案使用后,这更适合你想要实现的目标。用filter代替find,您就不需要做所有的事情了。

您可以使用它返回名称与用户输入匹配的对象。然后可以使用从找到的对象中获取javascript对象的属性名称和事实

请参见下面的工作示例:

const countryNameArray=[{ 名称:“法国”, 事实:“他们说法语” }, { 名称:‘比利时’, 事实:“他们说法语或荷兰语” }, ], wordGiven=提示输入国家名称; ifcountryObj=countryNameArray.find{name}=>name==wordGiven{ const{name,fact}=countryObj;//从countryObj获取名称和事实属性 alertname+':'+事实; }否则{ 提醒“我不明白,请给我一个国家的名字”;
}实际上,使用.filter的解决方案还不错,因为countryNameArray可能有许多同名的对象。但是,如果您确实使用了该方法,那么最好通过matchingCountries数组循环输出所有匹配项,而不仅仅是第一个匹配项@NickParsons表示同意,但我试图强调更多关于.filter部分的内容,然后说你可以做任何你喜欢的事情,例如。。。。也许我应该改变这个例子来强调你所说的。
var countryNameArray = [
    {
        name: 'France',
        fact: 'they speak french'
    },
    {
        name: 'Belgium',
        fact: 'they speak french or dutch'
    },
];

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