Alex Ironside
Alex Ironside

Reputation: 5039

Loop up to x numbers, or less

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++)

Upvotes: 4

Views: 78

Answers (4)

Nina Scholz
Nina Scholz

Reputation: 386560

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++) {
    //
}

Upvotes: 4

Nick Parsons
Nick Parsons

Reputation: 50684

You can use a ternary statement like so i < (i<arr.length ? 11 : arr.length):

function run_loop(arr) {
  for(let i=0; i < (i<arr.length ? 11 : arr.length); i++) {
    console.log(arr[i]);
  }
}

console.log("1st output");
run_loop([1, 2, 3, 4]); // Stops at 4 (doesn't try and print above the length of array)
console.log("2nd output:");
run_loop([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]); // Prints all values up to 11 (as specified in the for loop)

Upvotes: 1

Sahi
Sahi

Reputation: 1484

you can compare value of i with array length before the print statement as shown below

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++){
    //compare i and length
     if(i<arr.Length)
        console.log(arr[i]);
     else
       break;
}

Upvotes: -1

Rup
Rup

Reputation: 34408

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++)

Upvotes: 5

Related Questions