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

Array equal two different values and change a variable dynamically

本文关键字:动态 改变 变量 于两个 数组      更新时间:2023-09-26

我希望用户输入一个ID号。当用户单击按钮时,代码将查找一个包含所有 ID 号列表的数组,以检查它是否存在。然后,它将检查该ID号的价格。根据价格和查找的ID号,我希望它动态更改一个名为"成本"的变量。例如,用户在数字"5555"中键入代码会查找 ID 5555 是否存在,如果存在,它会检查该 id 的价格。基于这个价格,我希望它改变一个名为成本的变量。同样,如果我查找 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);
});