我对Object.entries()感到困惑 [英] I m confused with Object.entries()[i]

查看:45
本文介绍了我对Object.entries()感到困惑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经检查了此页面: mozilla文档

I have checked this page : mozilla documentation

我不明白为什么索引0为:

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 ?

推荐答案

文档说 Object.entries 返回给定对象的数组可枚举的属性 [key,value] 对.因此,是的,如果您看一下这句话,那会令人困惑

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'};

并最终在调用 Object.entries(object3)[0] 时得到 ["2","b"] .

执行此 Object.entries(object3)[0] 时,您正在访问此函数 Object.entries(object)返回的索引为0的一对.该数组的顺序与您首先定义 object3 的方式无关.根据文档的顺序与 for ... in 循环中.我在对象上运行了for ... in循环,这就是我得到的命令.

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 .

这就是为什么您得到 ["2","b"] 而不是 ["100","a"] 的原因.正如其他人在这里提到的那样,顺序似乎是那样的,因为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.

这篇关于我对Object.entries()感到困惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆