如何使用JavaScript在数组中查找特定单词?
要查找数组中的特定单词,可以使用include()。我们有以下数组-
var sentence = ["My Name is John Smith. My Favourite Subject is JavaScript. I live in US. I like Hockey"];
现在,下面是一个数组,其中包含我们需要在上述“句子”数组中搜索的单词-
var keywords = ["John", "AUS", "JavaScript", "Hockey"];
示例
以下是代码-
var keywords = ["John", "AUS", "JavaScript", "Hockey"];
var sentence = ["My Name is John Smith. My Favourite Subject is JavaScript. I live in US. I like Hockey"];
const matched = [];
for (var index = 0; index < sentence.length; index++) {
for (var outerIndex = 0; outerIndex < keywords.length; outerIndex++) {
if (sentence[index].includes(keywords[outerIndex])) {
matched.push(keywords[outerIndex]);
}
}
}
console.log("The matched keywords are==");
console.log(matched);要运行上述程序,您需要使用以下命令-
node fileName.js.
在这里,我的文件名为demo226.js。
输出结果
输出如下-
PS C:\Users\Amit\JavaScript-code> node demo226.js The matched keywords are== [ 'John', 'JavaScript', 'Hockey' ]
热门推荐
10 祝孙辈生日祝福语简短
11 恋人跨年祝福语大全简短
12 考大学敬酒简短祝福语
13 开工投产大吉祝福语 简短
14 偶然结婚祝福语朋友简短
15 感谢学长学姐祝福语简短
16 戏精的祝福语简短
17 我要结婚祝福语简短
18 婚前女儿生日祝福语简短