Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop up to x numbers, or less

Tags:

javascript

Let's say I have this code:

var arr = [0,1,2,3,4];

// This will work
for(let i=0;i<arr.length;i++){
  console.log(arr[i]);
}

// And this will crash
for(let i=0;i<11;i++){
  console.log(arr[i]);
}

I need to loop through, and print out 12 values by default. But sometimes let's say the database returns an array with only 2 elements in it. Then the loop will crash on arr[2].

On the other hand if the database returns an array with 100 elements, I want it to still only loop 12 times.

I could do a try catch inside of it, but that doesn't seem like a good practice.

for(let i=0;i<11;i++){
  try{
    console.log(arr[i]);
  }catch(e){

  }
}

It's all spaghetti now. I guess I could also check if the number is an undefined, like this:

// And this will crash
for(let i=0;i<11;i++){
  if(arr[i]!==undefined){
    console.log(arr[i]);
  }
}

But that still forces the loop to go 12 times. So is there a way of doing it, to make sure it will only run for as long as it's needed?

And there is also the break; way of doing things:

for(let i=0;i<11;i++){
  if(arr[i]!==undefined){
    console.log(arr[i]);
  } else{
    break;
    console.log('test'+i)
  }
}

But would there be a way to set the iterator limit like this?

for(let i=0; i<11 OR i<arr.length; i++)
like image 373
Alex Ironside Avatar asked Jan 03 '23 03:01

Alex Ironside


2 Answers

But would there be a way to set the iterator limit like this?

for(let i=0; i<11 OR i<arr.length; i++)

Yes, you can do exactly that, except you want to 'and' the conditions i.e. it has to be both less than 11 and less than the array length. The JavaScript boolean short-cut and operator is &&:

for(let i=0; i<11 && i<arr.length; i++)
like image 124
Rup Avatar answered Jan 13 '23 16:01

Rup


Instead of extend the check for either reaching the lenght of the array or 11, you could take the length of the array or 11 as minimum value for the check of the index.

for (let i = 0, l = Math.min(array.length, 11); i < l; i++) {
    //
}
like image 38
Nina Scholz Avatar answered Jan 13 '23 17:01

Nina Scholz