zoukankan      html  css  js  c++  java
  • for in 循环的输出顺序问题

     
               var data = {
                    '4': 'first',
                    '3': 'second',
                    '2': 'third',
                    '1': 'fourth'
                };
                for (var i in data) {
                    console.log(i + "  " + data[i])
                }
    

    IE11, chrome31, firefox23的打印如下:

     
    1  fourth
    2  third
    3  second
    4  first
    
     
    
    var obj = {
      "first":"first",
       "zoo":"zoo",
      "2":"2",
      "34":"34",
      "1":"1",
      "second":"second"
    };
    for (var i in obj) { console.log(i); };
    

    IE11, chrome31, firefox23的打印如下:

     
    
    1
    2
    34
    first
    zoo
    second
    

    根据stackoverflow给出的答案

    Currently all major browsers loop over the properties of an object in the order in which they were defined. Chrome does this as well, except for a couple cases. [...] This behavior is explicitly left undefined by the ECMAScript specification. In ECMA-262, section 12.6.4:
    The mechanics of enumerating the properties ... is implementation dependent.
    However, specification is quite different from implementation. All modern implementations of ECMAScript iterate through object properties in the order in which they were defined. Because of this the Chrome team has deemed this to be a bug and will be fixing it.
    All browsers respect definition order with the exception of Chrome and Opera which do for every non-numerical property name. In these two browsers the properties are pulled in-order ahead of the first non-numerical property (this is has to do with how they implement arrays). The order is the same for Object.keys as well.

    事实上,它不一定根据定义时的顺数输出,所有浏览器的最新版本现在都按chrome执行,先把当中的非负整数键提出来,排序好输出,然后将剩下的定义时的顺序输出。由于这个奇葩的设定,让avalon的ms-with对象排序不按预期输出了。只能强制用户不要以纯数字定义键名:

     
    
    var obj = {
      "first":"first",
       "zoo":"zoo",
      "2a":"2",
      "34u":"34",
      "1l":"1",
      "second":"second"
    };
    for (var i in obj) { console.log(i+" "+obj[i]); };
    

    IE11, chrome31, firefox23的打印如下:

     
    first first
    zoo zoo
    2a 2
    34u 34
    1l 1
    second second
    
  • 相关阅读:
    【CentOS 7】关于php留言本网站的搭建
    linux系统的初化始配置(临时生效和永久生效)
    时间同步ntp服务的安装与配置(作为客户端的配置)
    CentOS 7设置服务的开机启动
    辅助模型——通信图
    一.面向对象概论
    辅助模型——包图
    构建图
    部署图
    辅助模型——状态机图
  • 原文地址:https://www.cnblogs.com/rubylouvre/p/3396042.html
Copyright © 2011-2022 走看看