javascript – 如何通过将用户输入与其键匹配来显示对象的值?

我想制作转换工具,将一个代码(用户输入)转换为另一个代码(预定义)。 我决定使用Javascript对象作为代码的容器,我的函数将获取用户输入,这实际上是来自javascript对象的键,将其与Code容器中的键匹配,如果找到匹配,则该函数将显示值警报框。

我制作了一个代码,但它不起作用。 我试图找到解决方案但是现在,我失败了。

这是我的代码:

$(document).ready(function() { $("#convert").click(function(){ var GardinerToUnicodeCodePoint = { "A1" :"995328", "A1A" :"995329", "A1B" :"995330", "A1C" :"995331", "A2" :"995332", "A2A" :"995333", "A3" :"995334", "A3A" :"995335", "A3B" :"995336", "A4" :"995337", "A4A" :"995338", "A4B" :"995339", "A4C" :"995340", "A4D" :"995341", "A4E" :"995342", "A5" :"995343", "A5A" :"995344", "A5B" :"995345", "A5C" :"995346", "A6" :"995347", }; var userInput = $("#userInput").val; /*for example 'A1'*/ if (userInput in GardinerToUnicodeCodePoint) { alert(/*value of key 'userInput' -> 995328*/); } else { alert("No code found!"); } }); }); 

您可以在调用对象后使用[]来获取键值对:

 GardinerToUnicodeCodePoint[userInput] 

将您的代码更改为:

  var userInput = $("#userInput").val(); /*for example 'A1'*/ if (userInput in GardinerToUnicodeCodePoint) { alert(GardinerToUnicodeCodePoint[userInput]); } else { alert("No code found!"); } 

见jsfiddle: https ://jsfiddle.net/wy70s3gj/

 function getReturnCodeUsingKey(keyFromUserInput) { var GardinerToUnicodeCodePoint = { "A1" :"995328", "A1A" :"995329", "A1B" :"995330", "A1C" :"etc" }; returnVal = GardinerToUnicodeCodePoint[keyFromUserInput]; return returnVal ? returnVal : "error: no match found"; } 

将该函数传递给用户string inputstring input ,它将返回您想要的内容。

所以,你的完整解决方案看起来像这样:

 $(document).ready(function() { $("#convert").click(function(){ var userInput = $("#userInput").val(); /*for example 'A1'*/ // a call to our new function keeping responsibilities seperated return getReturnCodeUsingKey(userInput); }); }); function getReturnCodeUsingKey(keyFromUserInput) { var GardinerToUnicodeCodePoint = { "A1" :"995328", "A1A" :"995329", "A1B" :"995330", "A1C" :"995331", "A2" :"995332", "A2A" :"995333", "A3" :"995334", "A3A" :"995335", "A3B" :"995336", "A4" :"995337", "A4A" :"995338", "A4B" :"995339", "A4C" :"995340", "A4D" :"995341", "A4E" :"995342", "A5" :"995343", "A5A" :"995344", "A5B" :"995345", "A5C" :"995346", "A6" :"995347", }; // set a variable to hold the return of the object query returnVal = GardinerToUnicodeCodePoint[keyFromUserInput]; //return valid value from object, or string if undefined return returnVal ? returnVal : "error: no match found"; } 

@epascarello在评论中表达的问题是你应该使用$("#userInput").val(); 括号

代码示例:

 $('#convert').click(function() { var GardinerToUnicodeCodePoint = { A1: '995328', A1A: '995329', A1B: '995330', A1C: '995331', A2: '995332', A2A: '995333', A3: '995334', A3A: '995335', A3B: '995336', A4: '995337', A4A: '995338', A4B: '995339', A4C: '995340', A4D: '995341', A4E: '995342', A5: '995343', A5A: '995344', A5B: '995345', A5C: '995346', A6: '995347' }; var userInput = $('#userInput').val(); var result = userInput in GardinerToUnicodeCodePoint ? 'Value of key \'userInput\' -> ' + userInput : 'No code found!'; console.log(result); });