我在我的JavaScript文件上使用了JSLint。它抛出错误:

for( ind in evtListeners ) {

第41行字符9的问题:for in的主体应该是 包装在if语句中以过滤不需要的 原型中的属性。

这是什么意思?


当前回答

jslint的作者Douglas Crockford就这个问题写过(也说过)很多次。在他的网站的这一页上有一个部分是这样写的:

for Statement A for class of statements should have the following form: for (initialization; condition; update) { statements } for (variable in object) { if (filter) { statements } } The first form should be used with arrays and with loops of a predeterminable number of iterations. The second form should be used with objects. Be aware that members that are added to the prototype of the object will be included in the enumeration. It is wise to program defensively by using the hasOwnProperty method to distinguish the true members of the object: for (variable in object) { if (object.hasOwnProperty(variable)) { statements } }

Crockford还制作了一个关于YUI剧院的系列视频,在视频中他谈到了这一点。如果你对javascript有点兴趣,一定要看Crockford关于javascript的系列视频/演讲。

其他回答

瓦瓦的回答很中肯。如果使用jQuery,则使用$.each()函数处理这个问题,因此使用它更安全。

$.each(evtListeners, function(index, elem) {
    // your code
});

这意味着您应该使用hasOwnProperty方法筛选evtlistener的属性。

当然,这样说有点极端

...永远不要使用for in循环to 枚举数组。从来没有。使用 (var I = 0; 我< arr.length;我+ +)

?

道格拉斯·克罗克福德节选中的这部分值得强调

…第二种形式应该用with 对象……

如果你需要一个关联数组(又名哈希表/字典),其中键是命名的,而不是数字索引,你将不得不实现它作为一个对象,例如var myAssocArray = {key1: "value1", key2: "value2"…};

In this case myAssocArray.length will come up null (because this object doesn't have a 'length' property), and your i < myAssocArray.length won't get you very far. In addition to providing greater convenience, I would expect associative arrays to offer performance advantages in many situations, as the array keys can be useful properties (i.e. an array member's ID property or name), meaning you don't have to iterate through a lengthy array repeatedly evaluating if statements to find the array entry you're after.

无论如何,也感谢JSLint错误消息的解释,我将使用'isOwnProperty'检查现在通过我的无数关联数组交互!

坏的:(jsHint将抛出错误)

for (var name in item) {
    console.log(item[name]);
}

好:

for (var name in item) {
  if (item.hasOwnProperty(name)) {
    console.log(item[name]);
  }
}

老实说,添加一整行只是为了检查键是否存在,而使用应该迭代对象的键的语法会导致..无用的。只需使用Object.keys(obj)即可。替换为forEach(key => {})