简体   繁体   中英

Can Javascript objects be accessed like arrays?

Assuming an object is initialized as following:

var myObj = {
   "key1":"val1",
   "key2":"val2",
   "key3":"val3",
   ...
};

Can I retrieve key values like this?

var retrKey1 = myObj[0];
var retrKey2 = myObj[1];
var retrKey3 = myObj[2];
...

The issue I am trying to solve is that I need to pick random key values from this object. Generating a random number is not an issue, but:

  1. How can I retrieve the number of keys in the object/map?
  2. Can I retrieve the key values using a integer index like in arrays?

If not, what are my options?

No, because there's no ordering among property keys. If you want ordered keys, you need to work with an array.

You could define a structure like this :

var myObj = [
    {key:"key1", val:"val1"},
    ...
];

The Object.keys method returns an array of object properties. You can index the array with numbers then.

var myObj = {
 "key1":"val1",
 "key2":"val2",
 "key3":"val3",
 ...
};
var keys = Object.keys(myObj); 

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

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