2012-04-14 52 views
0

我希望用戶鍵入一個ID號。當用戶點擊一個按鈕時,代碼將查找一個包含所有ID號列表的數組,以檢查它是否存在。然後它會去檢查該號碼的價格。根據價格和查找的ID號碼,我想要這個動態地改變名爲「成本」的變量。因此,例如,用戶鍵入數字「5555」代碼查找ID 5555是否存在,如果存在,則檢查該ID的價格。基於這個價格,我希望它改變一個叫做成本的變量。同樣,如果我查了一個「1234」的ID。它會查找id,如果存在,獲得價格,然後更改名爲cost的變量。數組等於兩個不同的值並動態更改變量

我甚至不知道從哪裏開始。我正在考慮使用數組來映射ID號和價格,但我不知道這是否可行。我想要一個數字基本等於另一個數字,然後根據第二個數字更改一個變量,我想不出如何做到這一點。

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

回答

1

您可以使用一個對象作爲像對象一樣的字典。

// 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); 
}); 
+0

你能解釋一下嗎?我不明白這是如何工作的。 – Brian 2012-04-16 15:31:21

+0

@Brian我添加了評論。讓我知道如果這不會削減它。 – Chris 2012-04-16 16:11:49