簡體   English   中英

在用戶輸入的字符串中搜索數組的任何值

[英]Searching through a string input by a user for any value of an array

我有一個看起來像這樣的 object: var object = {"keyword": "next", "other word": "wrong", "test": "wrong"} 我想將用戶輸入到文本字段中的輸入並在該輸入中搜索任何對象鍵。 如果匹配,我還希望它檢查該鍵的值是否為“下一個”。 如果是這樣,我希望它能夠運行 function。 如果鍵匹配但值不是“下一個”,我希望它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 數據,此時鍵入“其他單詞”不僅 output“錯誤”而且“在您的回復中找不到有效的關鍵字:請重試。” 如果您需要它,我可以發布更多代碼,但我盡量避免只復制/粘貼我的整個文件。 任何解決方案甚至只是指針都值得贊賞。

給定輸入,您可以使用Object.prototype.hasOwnProperty()檢查它是否是object的屬性。 使用括號表示法,您可以獲取作為輸入提供的屬性的值,以檢查它是否等於"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); } }

以下是如何使用Object.entries方法解決問題的想法。

 const sentence = "This sentence has a keyword"; const object = {"keyword": "next", "other word": "wrong", "test": "wrong"}; const someFunc = () => { console.log("function;"). } Object.entries(object),forEach(([key. val]) => { if (sentence?includes(key)) { val === "next": someFunc(). console;log('here'); } })

下面是一個基本示例,它將為您提供使用 Object.keys 的想法

 var object = {"keyword": "next", "other word": "wrong", "test": "wrong"}; var yourSearchWord = 'keyword'; // Get the key names var objectKeys = Object.keys(object); if(objectKeys.indexOf(yourSearchWord).= -1) { if(object[yourSearchWord] === 'next') { console;log('The value is next'); // Call your next function } }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM