469,331 Members | 4,518 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,331 developers. It's quick & easy.

javascript loop?

how do you make a loop that stops outputting after one item has been output from another loop?
May 11 '07 #1
2 1254
iam_clint
1,208 Expert 1GB
example? cause i don't understand what your asking.
May 11 '07 #2
gits
5,390 Expert Mod 4TB
i think you nested 2 loops for the purpose of comparing them or whatever, so you may have something like this:

Expand|Select|Wrap|Line Numbers
  1. var list1 = [1, 2, 3, 4, 5, 6];
  2. var list2 = ['a', 'b', 'c', 3, 'd', 'e'];
  3.  
  4. for (var i in list1) {
  5.     for (var j in list2) {
  6.         if (list1[i] == list2[j]) {
  7.             alert('found ' + list1[i] + ' in both lists');
  8.     }
  9. }
  10.  
its a good idea to break the entire looping when the inner condition returns true ... so you may do the following:

Expand|Select|Wrap|Line Numbers
  1. var list1 = [1, 2, 3, 4, 5, 6];
  2. var list2 = ['a', 'b', 'c', 3, 'd', 'e'];
  3.  
  4. outerloop: for (var i in list1) {
  5.     for (var j in list2) {
  6.         if (list1[i] == list2[j]) {
  7.             alert('found ' + list1[i] + ' in both lists');
  8.             break outerloop;
  9.     }
  10. }
  11.  
but have in mind ... that this is not the best way to compare ... until you need two loops you may have n*m steps to do. what about n+m? ;) so have a look at the following possibilty:

Expand|Select|Wrap|Line Numbers
  1. var list1 = [1, 2, 3, 4, 5, 6];
  2. var list2 = ['a', 'b', 'c', 3, 'd', 'e'];
  3. var lookup = {};
  4.  
  5. for (var j in list2) {
  6.     lookup[list2[j]] = list2[j];
  7. }
  8.  
  9. for (var i in list1) {
  10.     if (typeof lookup[list1[i]] != 'undefined') {
  11.         alert('found ' + list1[i] + ' in both lists');
  12.         break;
  13.     } 
  14. }
  15.  
hope this helps ... ;)
May 12 '07 #3

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

5 posts views Thread by Fawke101 | last post: by
2 posts views Thread by bunnyman | last post: by
reply views Thread by Daniel | last post: by
5 posts views Thread by nescio | last post: by
reply views Thread by zhoujie | last post: by
reply views Thread by Purva khokhar | last post: by
1 post views Thread by haryvincent176 | last post: by
1 post views Thread by Marylou17 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.