开发者

"this[key]" on a for() in javacscript with prototype

开发者 https://www.devze.com 2023-03-25 12:55 出处:网络
I\'ve a JS error on the 5th line of this script (var el = this[key];). It works on FF, Chrome, Safari but not on IE. Someone can help me ?

I've a JS error on the 5th line of this script (var el = this[key];). It works on FF, Chrome, Safari but not on IE. Someone can help me ?

Object.prototype.between = function( value )
{
    var value = parseFloat(value);
    for (key in this) {         
        var el = this[key];
        var v = key.split('-');      开发者_Python百科   

        var min = parseFloat(v[0]);
        var max = parseFloat(v[1]);

        if (value >= min && value < max) { return el; }
    }
    return false;
}

Thanks for advance


You are most likely running into the "unfiltered for/in" problem. IE, when iterating for/in loops, runs across all properties and methods of an object to include those which it got from the prototype. This leads to several issues as your code usually assumes it is only going to encounter a certain kind of property. The most generic method of filtering for/in is shown below where I ensure that the current element is actually a property of the object being iterated and not just something which was inherited. You can get much more specific in such a check by ensuring that the current property is exactly the type, instance, or value you expect.

Object.prototype.between = function( value )
{
    var value = parseFloat(value);
    for (key in this) {         
        if( Object.prototype.hasOwnProperty.call( key, this ) ) {
            var el = this[key];
            var v = key.split('-');         

            var min = parseFloat(v[0]);
            var max = parseFloat(v[1]);

            if (value >= min && value < max) { return el; }
        }
    }
    return false;
}

As noted in the comments, there are other things you could do to your code to make it more solid and less error prone. You should start making a habit of running all your code through http://www.jshint.com

0

精彩评论

暂无评论...
验证码 换一张
取 消