0

Hi I am working on JavaScript Object.keys(). According to Mozilla, Object.keys() return an array whose elements are strings and the ordering of the properties is the same as that given by looping over the properties of the object manually. However, I did use Map, instead

let hashmap = {
        1000: 'M',
        900: 'CM',
        500: 'D',
        400: 'CD',
        100: 'C',
        90 : 'XC',
        50 : 'L',
        40 : 'XL',
        10 : 'X',
        9  : 'IX',
        5  : 'V',
        4  : 'IV',
        1  : 'I'  
    }

for (let key of Object.keys(hashmap)){
    console.log(key);
}


console.log(Object.keys(hashmap));

return value is Array ["1", "4", "5", "9", "10", "40", "50", "90", "100", "400", "500", "900", "1000"] I supposed to get the Array in the reversed order. Can any one tell me the reason why it looks like this ? Also, when looping over the object, it did not follow the order as well. Thanks! What is the root cause.

Jaden
  • 192
  • 4
  • 15
  • 1
    I believe the answer is found here: https://stackoverflow.com/questions/3186770/chrome-re-ordering-object-keys-if-numerics-is-that-normal-expected – Christian Oct 24 '20 at 19:30
  • Yes, they were kind of discussing about this question, but they did not say clearly the reason. Just like this is ECMAScript specification ! .... ! – Jaden Oct 24 '20 at 20:09
  • 1
    Not relevant to the question but just FYI: a [Map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) is different from an object literal (like `{ key: 'val', key2, 'etc' }`). – xdhmoore Oct 24 '20 at 22:40

1 Answers1

0

The result of "console.log(Object.keys(hashmap))" is exactly as expected - it should be in the order the data is stored, not the order in which it was added. See the example given by Mozilla under "array-like object with random key ordering".

When you manually loop over the object, you will get the same order (as it is stored). Another way to loop is:

for (let key in hashmap){
  console.log(key);
}
aminits
  • 174
  • 4
  • Thanks, I know the output will be like that, however, I have no idea why it is like that? – Jaden Oct 24 '20 at 20:07