I m confused with Object.entries()[i]

痴心易碎 提交于 2021-02-05 06:17:00

问题


I have checked this page : mozilla documentation

I dont understand why the index 0 with :

const object3 = { 100: 'a', 2: 'b', 7: 'c' };
console.log(Object.entries(object3)[0]);

// expected output: Array ["100", "a"] <== i thought of this

instead the documentation says you get :

// expected output: Array ["2", "b"]

Someone can explain it why ?


回答1:


The Docs say that Object.entries returns an array of given objects enumerable property [key,value] pairs . So yes its confusing if you look at this statement

const object3 = { 100: 'a', 2: 'b', 7: 'c' };

and end up getting ["2", "b"] when you call Object.entries(object3)[0].

When you are doing this Object.entries(object3)[0] , you are accessing a pair at the index of 0 returned by this function Object.entries(object) . The order of this array has nothing to do with how you defined the object3 in the first place. The order according to the doc is the same as the provided by a for...in loop. I ran the for...in loop on the object and this is what i got as the order.

2,7,100.

This is why you are getting ["2", "b"] instead of ["100", "a"]. As others have mentioned here , the order seems to be that way because 2<7<100.




回答2:


This is because the object has numeric keys and when you manipulate the object with the numeric keys the javascript sort the key-values in ascending order of the key value and since you have keys 2, 7, and 100. So, check this when you console.log the object Object.entries(object3) you get that sorted and when you access [0] you get Array ["2", "b"]

const object3 = { 100: 'a', 2: 'b', 7: 'c' };
console.log(Object.entries(object3));

Further clarification on sorting the object by ascending values of key when they are numeric. The javascript sorts them behind the scenes.

var a = {
  10: 'ten',
  5: 'five',
  11: 'eleven',
  1: 'one'
};
console.log(a);


来源:https://stackoverflow.com/questions/50653997/i-m-confused-with-object-entriesi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!