javascript-如何通过将用户输入与其键相匹配来显示对象的值? [英] javascript - How to show value from object by matching user input to its key?
问题描述
我想制作将一个代码(用户输入)转换为另一个(预定义)代码的转换工具.我决定将Javascript对象用作代码的容器,并且我的函数将接受用户输入,该输入实际上是javascript对象的键,将其与Code容器中的键匹配,如果找到匹配项,则函数将显示值警报框.
I want to make conversion tool which converts one code (user input) to another (predefined). I decided to use Javascript object as a container for codes, and my function will take user input which is actually a key from a javascript object, match it to the one in Code container and if the match is found, the function will display value to the alert box.
我编写了一个代码,但是它不起作用.我试图找到解决方案,但现在失败了.
I made one code, but it does not work. I tried to find the solution but for now, I failed.
这是我的代码:
$(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!");
}
});
});
推荐答案
调用对象以获取键值对后,可以使用[]
:
You can use []
after calling the object to get the key value pair:
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/
See jsfiddle: https://jsfiddle.net/wy70s3gj/
这篇关于javascript-如何通过将用户输入与其键相匹配来显示对象的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!