在JavaScript中执行循环的最佳方法是什么? [英] What is the best way to do loops in JavaScript

查看:152
本文介绍了在JavaScript中执行循环的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我偶然发现了几种在JavaScript中循环的方法,我最喜欢的是:

I have stumbled into several methods of looping in JavaScript, what I like the most is:

for(var i = 0; i < a.length; i++){
    var element = a[i];
}

但是经过测试( http://www.robertnyman.com/2008/04/11/javascript-loop-performance/ ) ,它应该写成使得长度只计算一次。

But as tested here (http://www.robertnyman.com/2008/04/11/javascript-loop-performance/), it should probably be written so that the length is only calculated once.

在jQuery中有一个.each,你可以坚持一个功能。我喜欢这个更好一点,因为我不需要输入两次数组,就像上面的解决方案一样。

In jQuery there is a .each that you can stick a function. I like this a little better, because I don't have to type the array twice, like in the above solution.

如果JavaScript支持宏,那么推出自己的宏将是件小事,但遗憾的是它没有。

If JavaScript supported macros it would be a piece of cake to roll your own, but sadly it does not.

那你们用什么?

推荐答案

我是在相关时开始使用迭代器。性能是合理的,但更重要的是它允许您封装循环逻辑:

I've started using iterators where relevant. Performance is reasonable, however more importantly it allows you to encapsulate the looping logic:

function createIterator(x) {
    var i = 0;

     return function(){
       return x[i++];
    };
}

然后使用:

var iterator=createIterator(['a','b','c','d','e','f','g']);

iterator();

返回a;

iterator();

返回b;

和等等。

迭代整个列表并显示每个项目:

To iterate the whole list and display each item:


var current;

while(current=iterator())
{
    console.log(current);
}

请注意,上述内容仅适用于迭代包含非虚假值的列表。如果此数组包含以下任何一项:

Be aware that the above is only acceptable for iterating a list that contains "non-falsy" values. If this array contained any of:


  • 0

  • false


  • null

  • NaN

  • 0
  • false
  • ""
  • null
  • NaN

上一个循环将停在那个项目上,而不是你想要/期望的那个。

the previous loop would stop at that item, not always what you want/expect.

为避免这种情况使用:

var current;

while((current=iterator())!==undefined)
{
   console.log(current);
}

这篇关于在JavaScript中执行循环的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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