Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how Object.keys(obj) works?

Tags:

javascript

As per the description of the Object.keys on MDN:

Object.keys returns an array whose elements are strings corresponding to the enumerable properties found directly upon object. The ordering of the properties is the same as that given by looping over the properties of the object manually.

It includes the following example:

// array like object with random key ordering
var an_obj = { 100: "a", 2: "b", 7: "c"};

alert(Object.keys(an_obj)); // will alert "2, 7, 100"

But as per the definition, key should be printed as 100, 2, 7 in the order they have been inserted in the object, instead of 2, 7, 100.

Please let me know, how the ordering of key happens in Object.key.

like image 988
niran Avatar asked Dec 26 '22 01:12

niran


1 Answers

I think you might have misunderstood this:

The ordering of the properties is the same as that given by looping over the properties of the object manually.

What this means is that the order of the properties in Object.keys is the same as if you did a for-in loop.

Compare the results of these:

var an_obj = { 100: "a", 2: "b", 7: "c"};

//using object.keys...
console.log(Object.keys(an_obj));

//using a manual loop...
for(var k in an_obj) { console.log(k); }

You will find the order for both these is the same.

like image 121
Jani Hartikainen Avatar answered Jan 08 '23 05:01

Jani Hartikainen