Home>Q&A>body text

javascript - Object.keys()与 for...in 遍历对象,输出的结果为什么是顺序的

问题:同上。谢谢

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

reply all(3)I'll reply

  • 大家讲道理

    大家讲道理2017-04-10 17:42:38

    根据 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...inObject 的结果吧

    这里也有一些讨论

    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

    reply
    0
  • 黄舟

    黄舟2017-04-10 17:42:38

    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的处理机制,
    根据一般的代码规范你这样使用本身就不合理~有些语言直接报错~

    reply
    0
  • 迷茫

    迷茫2017-04-10 17:42:38

    可以参看 这个书的介绍 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. 按添加顺序输出Symbolkey (es6 中新加的)

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

    reply
    0
  • Cancelreply