How to know if a break has been executed

3

Good, I have a doubt and I can not find an answer anywhere. The fact is that I have in a script a loop for in which I have a condition with a break statement. What I would like to know is if there is any way of knowing if the break sentence has been executed or not, without using auxiliary variables or logical variables.

This is the example:

var array = [];
var variable;

for (var i=0;i<array.length;i++) {
  if (array[i] === variable) {
    variable = i;
    break;
  }
}

Is there any way to evaluate if the break statement has been executed in this code? Does it return a Boolean value in any way?

    
asked by asantana o 26.10.2017 в 13:41
source

1 answer

3

I guess you're looking for something similar to for...else in Python. It is not possible, in Javascript, without the use of something else, to know if the loop has stopped con normalidad (Because it has reached the end) or because it stopped with a break .

But, are you sure that is what you want to check in your example? According to your example I see that what you want to check is if you have found an index.

var array = ['Javascript', 'mola', '=)'];
var variable = 'Javascript';
var index = -1;

for (var i=0;i<array.length;i++) {
  if (array[i] === variable) {
    index = i;
    break;
  }
}

if(index >= 0) {
  // Hacer algo
  console.log('index', index);
} else {
  console.log('No se encontró');
}

Or much simpler (ES2015):

var array = ['Javascript', 'no', 'es', 'Python', '=('];
var variable = 'Javascript';

var index = array.findIndex(item => item === variable);

if(index >= 0){
  console.log('index', index);
} else {
  console.log('No se encontró');
}
    
answered by 26.10.2017 / 14:03
source