你可以搜索你的陣列所需的對象之一,然後獲取該對象的值:
var value;
// Loop through the options array
for (var i = 0; i < options.length; i++) {
// If the key for this iteration's element is desired
if (options[i].key == "select") {
// Set the value to appropriately and exit the loop
value = options[i].value;
break;
}
}
這代碼根據您的密鑰使「值」等於您想要的值。如果要多次確定該值,可以將代碼包裝在函數中並返回值。您可能還想爲所需的密鑰添加參數,並用"options[i].key == <parameter name>"
替換options[i].key == "select"
。
或者,你可以組織你的對象,像這樣:
var options = {
"select": null,
"one": "First Option",
"second": "Second Option"
};
有了這個,你可以訪問所需的鍵的值,像這樣:
options[<desired key>]
所以,options["select"]
將返回null
。
@Jaromanda X感謝 – MemoryLeak