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

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

问题描述

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

for(var i = 0; i < a.length; i++){变量元素 = a[i];}

但正如这里测试的那样 (http://www.robertnyman.com/2008/04/11/javascript-loop-performance/),它可能应该被写成只计算一次长度.

在 jQuery 中有一个 .each 可以粘贴一个函数.我更喜欢这个,因为我不必像上面的解决方案那样输入两次数组.

如果 JavaScript 支持宏,那么你自己动手做就是小菜一碟,但遗憾的是它不支持.

那你们用什么?

解决方案

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

函数 createIterator(x) {变量 i = 0;返回函数(){返回 x[i++];};}

然后使用:

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

返回a";

迭代器();

返回b";

等等.

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

<上一页>无功电流;而(当前=迭代器()){控制台.log(当前);}

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

  • 0
  • 错误
  • "
  • NaN

上一个循环会停在那个项目上,并不总是你想要/期望的.

为了避免这种用法:

var 当前;而((当前=迭代器())!==未定义){控制台.log(当前);}

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];
}

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.

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.

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

So what do you guys use?

解决方案

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++];
    };
}

Then to use:

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

iterator();

returns "a";

iterator();

returns "b";

and so on.

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

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

To avoid this use:

var current;

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

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

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