使用Javascript:隐藏的原型方法循环? [英] Javascript: hiding prototype methods in for loop?

查看:165
本文介绍了使用Javascript:隐藏的原型方法循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此​​,可以说,我加入了一些原型方法,Array类:

So lets say I've added some prototype methods to the Array class:



Array.prototype.containsKey = function(obj) {
    for(var key in this)
        if (key == obj) return true;
    return false;
}

Array.prototype.containsValue = function(obj) {
    for(var key in this)
        if (this[key] == obj) return true;
    return false;
}


然后创建通过它的键的关联数组,并尝试循环:

then I create an associative array and attempt to loop through it's keys:



var arr = new Array();
arr['One'] = 1;
arr['Two'] = 2;
arr['Three'] = 3;

for(var key in arr)
   alert(key);

这将返回五个项目:

this returns five items:


  -One
  -Two
  -Three
  -containsKey
  -containsValue

但我想(希望?)只有三个。我是不是接近这一错了吗?有没有办法隐藏的原型方法?或者我应该做不同的东西吗?

but I want (expect?) only three. Am I approaching this wrong? is there a way to "hide" the prototype methods? or should I be doing something differently?

推荐答案

您可以使用JavaScript的的hasOwnProperty 方法在环路实现这一点,是这样的:

You can use JavaScript's hasOwnProperty method to achieve this in the loop, like this:

for(var key in arr) {
    if (arr.hasOwnProperty(key)) {
        ...
    }
}

参考:这YUI博客文章

这篇关于使用Javascript:隐藏的原型方法循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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