。includes()正在检查提示()中的关键字

问题描述 投票:0回答:2

我正在创建一种聊天机器人,它将在存储在数组中的嵌入式关键字上运行,在此示例中,我在x中检查了数组y。每当我在true中正确键入Hello时,都会返回prompt()。但是,如果我要在提示符下按“ Oh Hello There。”的方式讲,则返回false。如何检查prompt()(句子之间)内数组中的关键字

var x = ['Hello', 'Hi', 'Sup'];
var y = prompt("Looking for a Hello...");

if (x.includes(y)){
    alert("You Said Hello!");
} else {
    alert("No Hello Found!");
}
javascript arrays prompt
2个回答
0
投票

您需要检查每个单词,或使用此代码段中的正则表达式

var x = ['Hello', 'Hi', 'Sup'];
var y = prompt("Looking for a Hello...");

var containsX = x.some(word=>y.includes(word))

if (containsX){
    alert("You Said Hello!");
} else {
    alert("No Hello Found!");
}

0
投票

尝试使用indexof

As mdn says:

indexOf()方法返回调用字符串内的索引指定值首次出现的对象,从在fromIndex上搜索。如果找不到该值,则返回-1。

let x = ['Hello', 'Hi', 'Sup'];
let y = "Looking for a Hello...";

console.log(x.some(s=> y.indexOf(s)));
© www.soinside.com 2019 - 2024. All rights reserved.