使用Java中的if语句包装for循环-遍历数组 [英] Wrapping For in loops with if statements in Javascript -- looping over arrays

查看:170
本文介绍了使用Java中的if语句包装for循环-遍历数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

JSLint一直抱怨这样的事情

JSLint keeps complaining about things like this

var myArray = [1, 2, 3];
for (var value in myArray)
{
   // BLAH
}

说我应该将其包装在if语句中.我知道如果要遍历对象的属性,则需要包装它,但是在这里,我应该在if语句中添加什么内容以进行正确的过滤.

Saying that I should wrap it in an if statement. I realize you need to wrap it if you are looping over an object's properties, but here what should I put in the if statement to do the correct filtering.

另外,当我做类似的事情

Additionally when I do something like

for (var i = 0; i < 10; i++)
{
   // foo
}

for (var i =0; i < 20; i++)
{
   // bar
}

它抱怨说我已经被定义了.除了使用不同的变量名外,如何防止这种情况发生?

It complains that i has already been defined. How do I prevent this other than using different variable names?

推荐答案

JSLint抱怨很多,但这并不是真正有害的.在这种情况下,抱怨for...in是正确的,因为那是遍历数组的错误构造.

JSLint whinges about a lot that's not really harmful. In this case it's right to complain about for...in, because that's the wrong construct to loop over an Array.

这是因为您不仅将获得数字键,还将获得已添加到数组或其Array.prototype中的任何其他任意属性.后者通常来自框架添加的扩展实用程序功能.

This is because you will get not only the numeric keys, but also any other arbitrary properties that have been added to the array or its Array.prototype. The latter typically comes from extension utility functions added by frameworks.

虽然您可以用hasOwnProperty打败这种情况以检查它是否不是原型成员,但是这比仅用for (var i= 0...)正确地进行处理要丑陋,所以为什么要打扰呢.

Whilst you can defeat that case with hasOwnProperty to check it's not a prototype member, it's uglier than just doing it the proper way with for (var i= 0...) so why bother.

此外,使用for...in,您不一定会按预期的顺序获得项目.

Also, with for...in you won't necessarily get the items in numerical order as you might expect.

它抱怨说我已经被定义了.除了使用不同的变量名外,如何防止这种情况发生?

It complains that i has already been defined. How do I prevent this other than using different variable names?

是的,你可以忽略那个.

Yeah, you can ignore that one.

它希望您从第二个for (i...中删除var,因为在同一作用域中两次声明变量不会执行任何操作.但是,我建议将var留在此处,因为它不会造成任何危害,并且如果将循环移动到另一个块,则不希望它突然在全局变量上乱写.

It wants you to remove the var from the second for (i..., because declaring a variable twice in the same scope doesn't do anything. However I would recommend leaving the var there because it doesn't do any harm, and if you move the loop to another block you don't want it to be suddenly scribbling on globals.

这篇关于使用Java中的if语句包装for循环-遍历数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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