简体   繁体   中英

Better way to do nested for clauses

I have an array of data that I am going through, as well as an array of integers that represent individual items of the data array. My goal is to go through the data array one by one, and if the count of the item is in the integer array one thing will happen, and if it's not, another thing will happen.

To do this, I created two nested for clauses with an if statement and a Boolean toggle (representation of the code below). My question is whether there are other ways to do this, and what might be the advantage of doing it a different way (for example, if the data array gets big)?

var fp=false; //toggle
var data=array;  //array of data
var tog=array; //integer array for example, [7;22;53;2]

for (i=0; i<data.length; i++){
    for(j=0; j<tog.length; j++){
        if(i==tog[j]){
           fp=true;
           doSomething(i);
        };
    };
    if(fp==false){
       doSomething2(i);
    }
    else{
       fp=false;
    };
};

The nested for loop can be optimized as it is a "search" step, and you can do a better version than just to loop the whole thing, for example, if the numbers array is or can be sorted first, you can use binary search .

In ruby (and other modern languages), you can use iterators and built in methods to make the code more concise and potentially perform better (you can do benchmarking to verify that), for example, you can do something like:

data.size.times do |i|
  if tog[i]
    do_something(i)
  else
    do_something2(i)
  end
end

You can use indexOf-function instead of the inner for clause to make the code more readable.

for (i=0; i<data.length; i++){    
    if(tog.indexOf(parseInt(i)) > -1) {
           doSomething(i);
    } else {
           doSomething2(i);
    }
};

Disadvantage is that indexOf is slower than for clause, so I wouldn't recommend to use it if you care about performance. Source: http://jsperf.com/js-for-loop-vs-array-indexof/246 在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM