【问题标题】:Why is the first element undefined the second time I iterate through the collection为什么我第二次遍历集合时第一个元素未定义
【发布时间】:2016-02-19 21:05:58
【问题描述】:

在我的函数/对象中

this.StatusMappings = [
   {
       Range: [Infinity*-1, 50],
       Color: 'red',
       Text: 'Just getting started - will require considerable time to complete.'
   },
   {
       Range: [50, 70],
       Color: 'yellow',
       Text: 'Incomplete - major gaps exist and completion will take some time.'
   },
   {
       Range : [70, 90],
       Color : 'yellgreen',
       Text : 'Partially completed - but some gaps remain which can be completed shortly.'
   },
   {
       Range: [90, Infinity],
       Color: 'green',
       Text: 'Fully completed - no additional work needed.'
   }
];

this.UpdateInfo = function ( $slider, newval )
{
    var color = this.StatusMappings.firstOrUndefined(function (map) {
        console.log("map.Range = "); console.log(map.Range);//TEST
        return map.Range[0] >= newval && map.Range[1] < newval;
    });
    $slider.closest('.slider').addClass(color);
}

奇怪的是第一次调用UpdateInfo,一切都按预期进行,而第二次我得到了

未捕获的类型错误:无法读取未定义的属性“0”

因为我的//TEST我第一次看到它有效:

顺便说一下,我的辅助函数firstOrUndefined

Array.prototype.firstOrUndefined = function ( unpred )
{
    for ( var i in this ) 
        if ( unpred(this[i]) )
            return this[i];          
}

【问题讨论】:

  • 我相信这是您的for-in 循环的结果。 for-in 循环访问属性、方法和数组成员。我的猜测是 this[i] 成员可能是 Array.prototype 实例的属性或方法,而不是实际的 StatusMapping。

标签: javascript jquery


【解决方案1】:

在 JavaScript 中迭代数组时,使用for-in 循环绝不是一个好主意。最好使用for 循环遍历数组。 JavaScript 中的for-in 循环不仅访问数组成员,还访问数组原型属性和方法。我在 JSFiddle 中的测试表明我的假设是正确的,并且错误是由于 Array.prototype.firstOrUndefined() 扩展名被传递到您的 unpred 函数中,并且该函数没有 0 的属性。您可以通过将 for-in 循环更改为 for 循环来解决此问题。

Array.prototype.firstOrUndefined = function(unpred) {
  //Might be a good idea to validate unpred, too.
  if (typeof unpred === 'function') {
      for (var i = 0; i < this.length; i++)
        if (unpred(this[i]))
           return this[i];
  }
}

请参阅小提琴以获取参考。

https://jsfiddle.net/7bdj6j92/2/

有关不应将 for-in 循环与 JavaScript 数组一起使用的原因的更多信息:StackOverflow Answer

【讨论】:

  • 打败我,正要发布完全相同的东西。 :)
猜你喜欢
  • 2017-03-11
  • 1970-01-01
  • 1970-01-01
  • 2010-11-10
  • 1970-01-01
  • 2021-04-27
  • 1970-01-01
  • 2022-11-16
相关资源
最近更新 更多