Object.keys()和Object.values()方法返回保留相同顺序的数组 [英] Do Object.keys() and Object.values() methods return arrays that preserve the same order
问题描述
Object.keys()和 Object.values()方法返回保留相同顺序的数组?
Do Object.keys() and Object.values() methods return arrays that preserve the same order?
我的意思是,假设我们有以下对象:
I mean, suppose that we have the following object:
var obj = {};
obj.prop1 = "Foo";
obj.prop2 = "Bar";
如果我打电话给 obj.keys()
和 obj.values()
他们会以相同的订单返回属性吗?
If I call obj.keys()
and obj.values()
will they return properties with the same order?
prop1
prop2
Foo
Bar
或
prop2
prop1
Bar
Foo
对吧?
所以以下选项是不可能的,对吗?
So the following option is not possible, right?
prop1
prop2
Bar
Foo
推荐答案
简而言之,是。
两者 Object.keys
和 Object.values
(以及 Object.entries()
)通过 for-in
枚举对象的循环。
因为两者都使用相同的 [[Enumerate]]
,只要在具有相同未更改的原型的对象上调用它们(不删除或添加键之间的键
和值
调用),顺序将是相同的。
Both Object.keys
and Object.values
(and also Object.entries()
) enumerate via for-in
loop on the object.
Since both use the same [[Enumerate]]
, as long as they are called on an object with same unchanged own prototype (without deleting or adding keys between the keys
and values
calls), the order will be the same.
订单是什么?
这取决于如何初始化对象,您正在使用哪个资源管理器和您向对象插入附加键的顺序。
如果实际订单是对你来说很重要(并且不仅键
和值
结果将根据相同的顺序)防弹方法将使用数组。
What will the order be?
It depends on how you initialized your object, which explorer are you using and the order of which you have inserted additional keys to the object.
If the actual order is important to you as well (and not only that both keys
and values
result will be according to the same order) the bulletproof approach will be to use an array.
另一种方法: Object.entries()
将返回 [key,value]
对的列表(按照 for-in
循环提供的相同顺序同样)这可能对你的我们更有帮助案例。
A different approach: Object.entries()
will return a list of [key, value]
pairs (in the same order provided by a for-in
loop as well) which might be more helpful for your use case.
这篇关于Object.keys()和Object.values()方法返回保留相同顺序的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!