使用原型时停止 JavaScript 中的枚举 [英] Stopping enumeration in JavaScript when using prototype

查看:36
本文介绍了使用原型时停止 JavaScript 中的枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试在 JavaScript 中使用原型.

I'm currently trying to get my head around using prototype in JavaScript.

为了对此进行试验,我编写了一个函数,它可以有效地让您将 where 子句放在数组上:

To experiment with this, I've written a function that effectively works as allowing you to put a where clause onto arrays:

Array.prototype.where=(function(){
  var tmpArr=[],
      success;

  for (var x in this){
    var success=true;
    for (var i in arguments){
      if (this[x][arguments[i][0]]!=arguments[i][1]){
        success=false;
        break;
      }
    }

    if (success==true){
      tmpArr.push(this[x]);
    }
  }
  return tmpArr;
});

示例用法是:

arrayName.where([0, 'Fred'], [1, 'Bloggs']);

为了测试,这很有效.唯一的问题是,如果您当时要运行

For the sake of a test, this works pretty well. The only problem is if you were then to run

for (var x in someArrayHere){
  console.log(someArrayHere[x]);
}

你得到数组的输出,但有一个记录代表你已经原型化的函数.

You get the output the array, but with a record representing the function you've prototyped.

据我所知,这是通过将函数设置为不可枚举来排序的,但我找不到任何解释如何阻止它的文章.

As far as I can work out, this is sorted by setting the function as non-enumerable, but I can't find any articles explaining how to stop it.

我该怎么办?或者我每次都必须执行以下操作?

How would I go about it? Or would I have to do the below each time?

for (var x in someArray){
  if (typeof tSch[x]!="object"){
  }
}

推荐答案

for...in 构造枚举对象的所有属性(以及沿原型链继承的属性).当您将它与数组一起使用时,它将遍历 Array.prototype 的所有属性,以及数组的元素.

The for...in construct enumerates all properties of an object (and those inherited down the prototype chain). When you use it with an array, it will iterate over all properties of Array.prototype, as well as the elements of the array.

使用普通的 for 循环来防止这种情况:

Use a normal for loop to prevent this:

for(var x = 0; x < this.length; x++) {
    //Do stuff
}

这篇关于使用原型时停止 JavaScript 中的枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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