[英]Do the keys of JavaScript associative arrays need to be strings, or can they be any object?
[英]Finding Keys in associative arrays with JavaScript
有了這個關聯數組,我想找到一個特定的鍵:
var veggie_prices = new Array();
veggie_prices["serves6"] = 20;
veggie_prices["serves8"] = 25;
veggie_prices["serves10"] = 35;
如果我遍歷數組,則可以使用以下命令找到值:
var x = veggie_prices[i].value;
但是如何找到鑰匙?
var y = veggie_prices[i].key;
要直接回答您的問題,請使用for..in
循環
var veggie_prices = new Array();
veggie_prices["serves6"] = 20;
veggie_prices["serves8"] = 25;
veggie_prices["serves10"] = 35;
for (var i in veggie_prices) {
console.log(i); // output: serves6, etc..
}
但是,要清楚一點,javascript沒有關聯數組。 您擁有的是一個類型為array的對象,除了正常的索引(盡管目前為空)和其他本機數組的屬性/方法(例如.length
, .pop()
等.pop()
,您僅向其添加了幾個屬性。 ..)
為什么要使用數組? 您可以改用一個對象嗎?
var veggie_prices = {};
veggie_prices["serves6"] = 20;
veggie_prices["serves8"] = 25;
veggie_prices["serves10"] = 35;
Object.keys(veggie_prices).forEach((key) => {
console.log('Key is: ' + key);
console.log('Value is: ' + veggie_prices[key]);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.