2016-08-04 35 views
0

关联数组有了这个关联数组,我想找到一个specfic键:查找键在使用JavaScript

var veggie_prices = new Array(); 
veggie_prices["serves6"] = 20; 
veggie_prices["serves8"] = 25; 
veggie_prices["serves10"] = 35; 

如果通过阵列的I循环,我能找到的值:

var x = veggie_prices[i].value; 

但是如何找到钥匙?

var y = veggie_prices[i].key; 

回答

3

直接回答你的问题,用一个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没有关联数组。除了普通(尽管此时为空)索引和其他本地数组属性/方法(例如.length,.pop()等)之外,您拥有的是阵列类型的对象,并且您只是向其添加了多个属性

+0

so ..为什么downvote –

+0

我不明白为什么这被拒绝了。 – mrvncaragay

+0

仅添加上下文 - 目前,此列表正在使用单选按钮控件在列表中进行选择。要找到带有for循环的选定单选按钮,我使用.checked方法和.value来获取值。使用.key不会产生密钥。不知道为什么。谢谢您的回答。 – windsurf88

2

你为什么使用数组?你可以使用一个对象吗?

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

是的将移动到对象。目前,此列表正在使用单选按钮控件在列表中进行选择。要找到所选的单选按钮,我使用.checked方法和.value来获取值。使用.key不会产生密钥。不知道为什么。谢谢您的回答。 – windsurf88

+0

很高兴帮助!如果有的话,请接受答案。 – sma