如何检查字符串的一部分是否在数组中?

时间:2017-04-08 19:58:39

标签: javascript arrays

user_input = "";
answer = "";

Array.greeting = ["hi", "hello"]
Array.names = ["john","james"]

user_input = document.getElementById('user_input').value.toLowerCase();
document.getElementById('text_input').innerHTML = user_input;

documnet.getElementById('say_something').innerHTML = say;
if(""){}
else{}
if(Array.greeting.includes(user_input) > 0){
    say = "Hello";
}
if(Array.names.includes(user_input) > 0){
    say = "User";
}

这就是我所理解的并且已经启动并运行了正确的输出,但我怎么能使用输入“hi john”并获得“Hello User”的输出而不将其烘焙成阵列?

2 个答案:

答案 0 :(得分:0)

让我们简化您的要求: 你想检查数组中是否有任何元素" arr"包含字符串" s"。

的一部分
var check = function(arr, s) {
  for (var i = 0; i < arr.length; i++) {
    if (s.indexOf(arr[i]) > -1) {
      return true;
    }
  }
  return false;
}

答案 1 :(得分:0)

你可以这样做:

&#13;
&#13;
var greetings = ["hi", "hello"];
var names = ["john","james"];

submit.onclick = function () {
    // Split input into words, and convert that array to a Set for fast lookup
    var words = new Set(user_input.value.split(/\s+/));
    // Choose a greeting that is not among the input words.
    // If all of them occur in the input, take the first greeting word
    var greeting = greetings.find( greeting => !words.has(greeting)) || greetings[0]; 
    // Choose a name that is not among the input words (or take the first)
    var name = names.find( name => !words.has(name)) || names[0];
    // Output with textContent (not innerHTML!)
    text_input.textContent = user_input.value;
    say_something.textContent = greeting + ' ' + name;
}
&#13;
Input: <input id="user_input"><button id="submit">Submit</button><br>

You said: <span id="text_input"></span><br>
Reply: <span id="say_something"></span>
&#13;
&#13;
&#13;

显然,当你同时输入&#34; hi&#34;并且&#34;你好&#34;,代码将找不到要使用的问候语。在这种情况下,它使用数组中的第一个问候语(&#34; hi&#34;)。同样的原则适用于名称。