首页 > 解决方案 > 在用户输入的字符串中搜索数组的任何值

问题描述

我有一个看起来像这样的对象:var object = {"keyword": "next", "other word": "wrong", "test": "wrong"}. 我想将用户输入到文本字段中的输入并在该输入中搜索任何对象键。如果匹配,我还希望它检查该键的值是否为“下一个”。如果是这样,我希望它能够运行一个功能。如果一个键匹配但该值不是“下一个”,我希望它console.log为该值。

这是我目前正在使用的代码:

var object = {"keyword": "next", "other word": "wrong", "test": "wrong"}
var match;
document.addEventListener('keyup', function(e){
    var text = document.getElementById("input").value;
    var options = Object.keys(object);
    if (e.keyCode == 13){
      if(options.some(function(element){
        match = element;
        return text.toString().indexOf(element) != -1;
      })){
        if (object[match].toString() == "next"){
          console.log("next");
          document.getElementById("input").value = "";
        } else {                         
          console.log(object[match]);
          document.getElementById("input").value = "";
        }
    } else {
      document.getElementById("input").value = "";
      console.log("A valid keyword could not be found in your response: please try again!");
    }
  }
});
<input id='input' autofocus>
<div id="gamearea"></div>

此代码工作正常,直到我更改对象数据时输入“其他单词”不仅会输出“错误”,还会输出“在您的响应中找不到有效关键字:请重试!” 如果您需要它,我可以发布更多代码,但我尽量避免只复制/粘贴我的整个文件。任何解决方案甚至只是指针都值得赞赏。

标签: javascriptarraysjavascript-objects

解决方案


给定一个输入,您可以检查它是否是您objectusing的属性Object.prototype.hasOwnProperty()。使用括号表示法,您可以获取作为输入提供的属性的值,以检查它是否等于"next"

var object = {"keyword": "next", "other word": "wrong", "test": "wrong"};
var userInput = "keyword";

if(object.hasOwnProperty(userInput)) { // check that user input is a property . in object
  var value = object[userInput]
  if(value === "next") { // check that the value of the users input is "next"
    // run some function
    console.log("Value next, so we can call a function");
  } else { // the value is not next, so we can log it
    console.log(value);
  }
}


推荐阅读