首页 > 解决方案 > 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;
  }

标签: javascript

解决方案


推荐阅读