在我的函数/对象内我有
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
被调用,一切都按预期进行,而第二次我得到 p>
Uncaught TypeError: Cannot read property '0' of undefined
因为我的//TEST
我第一次看到它有效:
顺便说一句,我的辅助函数firstOrUndefined
是
Array.prototype.firstOrUndefined = function ( unpred )
{
for ( var i in this )
if ( unpred(this[i]) )
return this[i];
}
最佳答案
在 JavaScript 中迭代数组时,使用 for-in
循环绝不是一个好主意。最好使用 for 循环来迭代数组。 JavaScript 中的 for-in 循环不仅访问数组成员,还访问数组原型(prototype)属性和方法。我在 JSFiddle 中的测试表明我的假设是正确的,并且错误是由于 Array.prototype.firstOrUndefine()
扩展被传递到您的 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];
}
}
请参阅 fiddle 以供引用。
https://jsfiddle.net/7bdj6j92/2/
有关为什么不应在 JavaScript 数组中使用 for-in
循环的更多信息:StackOverflow Answer
关于javascript - 为什么第二次迭代集合时第一个元素未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35515022/