首页 > 解决方案 > 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!");
        }
    });
});

标签: javascriptjqueryobjectconverter

解决方案


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

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/


推荐阅读