javascript - Object.keys()与 for...in 遍历对象,输出的结果为什么是顺序的
迷茫
迷茫 2017-04-10 17:40:38
0
3
722

问题:同上。谢谢

var obj = { "b1" : "a", "b2" : "b2", 7: "c", 4: 'dd'};
console.log(Object.keys(obj)); //输出["4", "7", "b1", "b2"]
迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

reply all(3)
大家讲道理

根据 MDN 上的解释

The Object.keys() method returns an array of a given object's own enumerable properties, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).

Object.key 的顺序是根据 for...in 决定的

规范里说到

The mechanics of enumerating the properties is implementation dependent. The order of enumeration is defined by the object.

而且

It is an unordered collection of properties each of which contains a primitive value, object, or function. A function stored in a property of an object is called a method.

Object 是个无序的集合

所以应该是各个浏览器实现 for...in Object 的结果吧

这里也有一些讨论

http://stackoverflow.com/questions/280713/elements-order-in-a-for-in-loop
http://stackoverflow.com/questions/30076219/does-es6-introduce-a-well-defined-order-of-enumeration-for-object-properties

黄舟

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

这里有Object.keys的文档

首先 Object.keysfor in 顺序没任何区别

// 数字开头的key 合理?
var obj = { "b1" : "a", "b2" : "b2", 7: "c", 4: 'dd'};

// 如果这样你再试试?你说的排序不成立了吧~!!!!!!!!!~
var obj = { "b3" : "a", "b2" : "b2", 7: "c", 4: 'dd'};

答案很简单只有数字的部分会放到最前面然后排序 其他部分会放到后面 这只是js的处理机制,
根据一般的代码规范你这样使用本身就不合理~有些语言直接报错~

迷茫

可以参看 这个书的介绍 http://exploringjs.com/es6/ch_oop-besides-classes.html#sec_iterating-property-keys

  1. Object.keys()for...in 输出顺序一样

  2. 输出顺序规则为:

  1. 按(integer indices)升序输出

  2. 按添加顺序输出字符串key

  3. 按添加顺序输出Symbol key (es6 中新加的)

integer indices : 是指将key转化为53bit的无符号整型,然后再转会字符串 后依旧相等的 key。如 '10', '2' 为integer indices。 '01', '12a' 不是 integer indices。

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!