javascript - 在用户输入的字符串中搜索数组的任何值
问题描述
我有一个看起来像这样的对象: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>
此代码工作正常,直到我更改对象数据时输入“其他单词”不仅会输出“错误”,还会输出“在您的响应中找不到有效关键字:请重试!” 如果您需要它,我可以发布更多代码,但我尽量避免只复制/粘贴我的整个文件。任何解决方案甚至只是指针都值得赞赏。
解决方案
给定一个输入,您可以检查它是否是您object
using的属性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);
}
}
推荐阅读
- google-app-engine - 部署在 Google App Engine 上的应用的 /healthz 路由返回 404
- java - 为什么我们在初始化时要传递集合(或任何对象)的引用?请检查下面的代码
- markdown - 如何在 GitHub 的自述降价文件中使标题可折叠?
- visual-studio-code - 用于 VS 代码的更漂亮的代码格式化程序失败,并显示“没有为扩展名“.cjs”指定加载程序”
- javascript - 按特定术语读取 JSON 值
- javascript - 录制的宏在多个选项卡或全部上运行
- loops - For循环正在打印每隔一行,我需要它来打印每一行
- node.js - TypeError:无法读取未定义、未定义错误的属性“连接”
- apache-kafka - 当源连接器无法暂停时,如何为现有主题的新消费者组配置偏移量
- c# - 如何使用但基于其他子句 LINQ 从集合列表中获取最旧的日期