javascript - javascript - 如何通过将用户输入与其键匹配来显示对象的值?
问题描述
我想制作将一个代码(用户输入)转换为另一个(预定义)的转换工具。我决定使用 Javascript 对象作为代码容器,我的函数将获取用户输入,这实际上是来自 javascript 对象的键,将其与代码容器中的匹配,如果找到匹配项,该函数将显示值警报框。
我做了一个代码,但它不起作用。我试图找到解决方案,但现在我失败了。
这是我的代码:
$(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/
推荐阅读
- python - 我想将我的目标文件保存为 .CSV 而不是 xlsx
- typescript - SyntaxError: Unexpected token {, ES6 Imports
- c++ - 有人可以解释这个链式模板实例化吗?
- javascript - 使用 fetch 向谷歌云函数发送一个帖子请求,其中一个对象作为主体不起作用
- assembly - 我不断收到第 57 行的 A2008 错误。我似乎找不到错误是什么。“退出”应该没问题
- python - 用for循环替换JSON列表中的Python?
- python - SQLAlchemy / SQL 索引与 Pandas 中的索引相比如何?
- sql - Msg 120, Level 15, State 1, Procedure Generate_Exame, Line 6, INSERT 语句的选择列表包含的项少于插入列表
- cordova - 由于 cordova-plugin-meteor-webapp 中的“下载资产错误”,热代码推送失败
- python - AttributeError:“collections.OrderedDict”对象没有属性“train”