简体   繁体   中英

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

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. 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..)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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