Javascript 数组等于两个不同的值并动态更改变量

Javascript 数组等于两个不同的值并动态更改变量,javascript,arrays,variables,equals,Javascript,Arrays,Variables,Equals,我希望用户输入一个ID号。当用户单击一个按钮时,代码将查找一个包含所有id号列表的数组,以检查它是否存在。然后,它将检查该id号的价格。根据价格和查找的ID号,我希望动态更改名为“成本”的变量。例如,一个用户键入号码“5555”,代码会查找ID 5555是否存在,如果存在,它会检查该ID的价格。根据该价格,我希望它更改一个名为cost的变量。同样,如果我查找一个id“1234”。它将查找id,如果它存在的话,得到价格,然后更改称为成本的变量 我甚至不知道从哪里开始。我曾考虑使用数组来映射id号和

我希望用户输入一个ID号。当用户单击一个按钮时,代码将查找一个包含所有id号列表的数组,以检查它是否存在。然后,它将检查该id号的价格。根据价格和查找的ID号,我希望动态更改名为“成本”的变量。例如,一个用户键入号码“5555”,代码会查找ID 5555是否存在,如果存在,它会检查该ID的价格。根据该价格,我希望它更改一个名为cost的变量。同样,如果我查找一个id“1234”。它将查找id,如果它存在的话,得到价格,然后更改称为成本的变量

我甚至不知道从哪里开始。我曾考虑使用数组来映射id号和价格,但我不知道这是否可行。我希望一个数本质上等于另一个数,然后根据第二个数改变一个变量,我想不出怎么做

id[0] = new Array(2)
id[1] = "5555";
id[2] = "6789";
price = new Array(2)
price[0] = 45;
price[1] = 18;

可以将对象用作类似字典的对象

// Default val for cost
var cost = -1;

// Create your dictionary (key/value pairs)
// "key": value (e.g. The key "5555" maps to the value '45')
var list = {
    "5555": 45,
    "6789": 18
};

// jQuery click event wiring (not relevant to the question)
$("#yourButton").click(function() {
    // Get the value of the input field with the id 'yourInput' (this is done with jQuery)
    var input = $("#yourInput").val();

    // If the list has a key that matches what the user typed,
    // set `cost` to its value, otherwise, set it to negative one.
    // This is shorthand syntax. See below for its equivalent
    cost = list[input] || -1;

    // Above is equivalent to
    /*
    if (list[input])
        cost = list[input];
    else
        cost = -1;
    */

    // Log the value of cost to the console
    console.log(cost);
});

你能再解释一下吗?“我不明白这是怎么回事。”布赖恩补充道。如果这还不够,请告诉我。