Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
427 views
in Technique[技术] by (71.8m points)

jquery - What is the best way to do loops in 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];
}

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...