"该[键] QUOT;在带有原型的javacscript中的for()上 [英] "this[key]" on a for() in javacscript with prototype

查看:92
本文介绍了"该[键] QUOT;在带有原型的javacscript中的for()上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这个脚本的第5行有一个JS错误(var el = this [key];)。它适用于FF,Chrome,Safari但不适用于IE。有人可以帮帮我吗?

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('-');         

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

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

感谢提前

推荐答案

您最有可能遇到未经过滤的问题。当迭代for / in循环时,IE遍历对象的所有属性和方法,以包括它从原型获得的那些属性和方法。这导致了一些问题,因为您的代码通常认为它只会遇到某种属性。最常用的for / in过滤方法如下所示,我确保当前元素实际上是被迭代对象的属性,而不仅仅是被继承的东西。通过确保当前属性与您期望的类型,实例或值完全相同,您可以在此类检查中获得更具体的信息。

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;
}

如评论中所述,您还可以对代码执行其他操作使其更坚固,更不容易出错。您应该开始养成通过 http://www.jshint.com 运行所有代码的习惯

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

这篇关于&QUOT;该[键] QUOT;在带有原型的javacscript中的for()上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆