【问题标题】:for..in loop loops over non-numeric indexes “clean” and “remove”for..in 循环遍历非数字索引“clean”和“remove”
【发布时间】:2015-03-24 13:30:25
【问题描述】:

这是我可能在这里遗漏的非常基本的东西,但直到现在我还没有看到这样的结果。

我有一个 for 循环,其中 options.headers.length 是 3。在 for 循环中,我正在动态创建表头。理想情况下,这个循环应该为0 1 and 2 运行三次,但是当我打印索引时,它正在打印0,1,2,clean and remove。我还没有看到clean and remove 作为索引。我知道这些信息还不够,但如果您有任何线索,请提出建议。在调试之后,我也得出了结论。

for (index in options.headers)

【问题讨论】:

  • 对于数组,您应该使用简单的for 循环,而不是for in 循环:类似于for (var index = 0, len = options.headers.length; index < len; i++)
  • clean 和 remove 是属性.. 当您使用 (for in) 时,它假定 option.header 作为一个对象,它将获取与其对象相关的所有键。您必须改用@Andy 解决方案。
  • 来自 MDN:[[for..in] 遍历对象及其原型链的所有可枚举属性](developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/…)
  • 没有人缓存他们数组的长度了吗:/
  • for in 循环如何在一个页面上工作而在另一个页面上不起作用。在一个页面中它迭代了 3 次,另一个迭代了 5 次。应该是一致的

标签: javascript jquery for-loop


【解决方案1】:

如果您不想迭代 cleanremove,则将循环更改为:

for (var i=0; i< options.headers.length;i++){
//use i for getting the array data
}

如果您使用for (index in options.headers),它还将迭代non-numeric 键。

【讨论】:

    【解决方案2】:
    1. 不要只使用索引(因为那是 = window.index = global = bad)使用 var index (在这里阅读更多https://www.google.pl/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=globals+javascript+bad

    2. 你必须检查数组是否有它作为自己的属性或者它的某些功能(更多答案后)


    for (var index in options.headers) {
        if (options.headers.hasOwnProperty(index) {
             // code here
        }
    }
    

    更多关于#2:

    假设我们有

    var array = [0,1,2,3];
    

    除此之外,用函数扩展数组(数组也可以在javascript和字符串中具有函数)

    Array.prototype.sayHello = function() {
        alert('Hello');
    };
    

    然后你的循环会打印 sayHello 作为数组的一部分,但这不是它自己的属性,只有数组

    【讨论】:

      【解决方案3】:

      我假设 options.headers 是一个数组?

      当您(或您加载的某些框架)向 Array 原型添加方法时,就会发生这种情况。 “for in”循环也将枚举这些添加的方法。因此,您应该使用以下方法对数组进行循环:

      for (var i = 0; i < options.headers.length; i++)
      

      这样你只会得到真正的值而不是添加的方法。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-11-07
        • 1970-01-01
        • 2015-12-18
        • 1970-01-01
        • 2022-06-30
        相关资源
        最近更新 更多