简体   繁体   English

使用JavaScript在关联数组中查找键

[英]Finding Keys in associative arrays with JavaScript

With this associative array, I would like to find a specfic key: 有了这个关联数组,我想找到一个特定的键:

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

If I loop through the array, I can find the values with: 如果我遍历数组,则可以使用以下命令找到值:

var x = veggie_prices[i].value;

but how should the key be found ? 但是如何找到钥匙?

var y = veggie_prices[i].key;

To directly answer your question, use a for..in loop 要直接回答您的问题,请使用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..
}

However, just to be clear, javascript does not have associative arrays. 但是,要清楚一点,javascript没有关联数组。 What you have is an object of type array, and you just added several properties to it, in addition to the normal (albeit empty at the moment) index and other native array properties/methods (eg .length , .pop() , etc..) 您拥有的是一个类型为array的对象,除了正常的索引(尽管目前为空)和其他本机数组的属性/方法(例如.length.pop().pop() ,您仅向其添加了几个属性。 ..)

Why are you using an array? 为什么要使用数组? Can you use an object instead? 您可以改用一个对象吗?

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM