gpt4 book ai didi

javascript - Object.keys(obj) 如何工作?

转载 作者:行者123 更新时间:2023-12-03 18:36:58 24 4
gpt4 key购买 nike

根据 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.



它包括以下示例:
// 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"

但根据定义, key 应打印为 100, 2, 7按照它们插入对象的顺序,而不是 2, 7, 100 .

请让我知道, Object.key 中的 key 排序是如何发生的.

最佳答案

我想你可能误解了这一点:

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



这意味着 Object.keys 中属性的顺序与执行 for-in 循环时相同。

比较这些结果:
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); }

你会发现这两个的顺序是一样的。

关于javascript - Object.keys(obj) 如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17348292/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com