javascript - Javascript变量Const.prompts能用吗?
问题描述
是否有可能为此设计一个 JavaScript,而不是只考虑某些单词而不是整个句子。例如:用户 X 通过输入输入一个问题:“今天是星期几?” 该脚本不会在答案选项中查找整个句子和拼写,而是找到“day”并输出存储的答案。
const prompts = [
["why not", "which day is today", "what time is it", "why "],
const replies = [
["there for", "a sunny Day", "you're late", "I don't know"],
和 index.js
function output(input) {
let product;
// Regex remove non word/space chars
// Trim trailing whitespace
// Remove digits - not sure if this is best
// But solves problem of entering something like 'hi1'
let text = input.toLowerCase().replace(/\u00e4/g, "ae").replace(/\u00f6/g,
"oe").replace(/\u00fc/g, "ue").replace(/\u00df/g, "ss").trim();
text = text
.replace(/ a /g, " ") // 'tell me a story' -> 'tell me story'
.replace(/i feel /g, "")
.replace(/whats/g, "what is")
.replace(/please /g, "")
.replace(/ please/g, "")
.replace(/r u/g, "are you");
if (compare(prompts, replies, text)) {
// Search for exact match in `prompts`
product = compare(prompts, replies, text);
} else if (text.match(/thanks/gi)) {
product = "youre welcome!"
} else if (text.match(/(sun|clouds|weather)/gi)) {
// If no match, check if message contains `cloudsweather`
product = cloudsweather[Math.floor(Math.random() * cloudsweather.length)];
} else {
// If all else fails: random alternative
product = alternative[Math.floor(Math.random() * alternative.length)];
}
// Update DOM
addChat(input, product);
}
function compare(promptsArray, repliesArray, string) {
let reply;
let replyFound = false;
for (let x = 0; x < promptsArray.length; x++) {
for (let y = 0; y < promptsArray[x].length; y++) {
if (promptsArray[x][y] === string) {
let replies = repliesArray[x];
reply = replies[Math.floor(Math.random() * replies.length)];
replyFound = true;
// Stop inner loop when input value matches prompts
break;
}
}
if (replyFound) {
// Stop outer loop when reply is found instead of iterating through the entire array
break;
}
}
return reply;
}
解决方案
推荐阅读
- python - Python Eve 中嵌套字段的投影
- android - React Native ScrollView 裁剪 Android Landscape 上的最后一个元素
- asp.net - .NET - SelectedRow 不返回任何值
- c# - c#文本框显示对象名称而不是值
- r - 在我的 R 代码中观察到异常的逻辑不一致
- javascript - 如何在 React 中访问组件方法?
- python-3.x - 如何在 mac Os 中将 openCv 与 Python3 链接起来
- javascript - 知道数组的 jqXHR 何时全部完成
- java - 如何在 Linux 操作系统中从 Java 调用“Powershell 脚本文件”
- javascript - 下拉菜单项行为