-2

please help solve the problem.

live example is here: https://jsfiddle.net/oqc5Lw73/

i generate several tank objects:

var Tank = function(id) { 
    this.id = id; 
    Tank.tanks.push(this);
}

Tank.tanks = [];

for (var i = 0; i < 3; i++) {
  new Tank(i);
}

Tank.tanks.forEach(function(tank, i, arr) {
  console.log(tank);         
});  

console.log('summary tanks: ' + Tank.tanks.length);

after i delete tank with random index:

var tankDel = Math.floor(Math.random() * (3));

Tank.tanks.splice(tankDel, 1);
Tank.count -= 1; 

Tank.tanks.forEach(function(tank, i, arr) {
  console.log(tank);         
});  

console.log('summary tanks: ' + Tank.tanks.length);

i try check tanks massive. if tanks massive contain tank with property 'id' = 0 then i need display alert('tank with id 0 is dead').

but console output follow error message:

Uncaught SyntaxError: Illegal break statement

stackow101
  • 121
  • 6

4 Answers4

0

You can't quit from forEach using break. Just remove break, and it will work.

P.S: honestly, it is better to refactor that code:)

dimko1
  • 872
  • 7
  • 15
0

break is to break out of a loop like for, while, switch etc which you don't have here, you need to use return to break the execution flow of the current function and return to the caller. See similar post here: illegal use of break statement; javascript

Tank.tanks.forEach(function(tank, i, arr) {
  if(tank.id == 0) {
    tank0Dead = false;
    return;
  };       
});  

if(tank0Dead == true) {
  alert('tank with id 0 is dead');
};

jsfiddle : https://jsfiddle.net/oqc5Lw73/6/

Community
  • 1
  • 1
Hasta Tamang
  • 2,205
  • 1
  • 18
  • 17
0

Your only problem is that you can't use the break; statement in a forEach function.

But you can in a for() loop, so here is the equivalent code with a for :

for (var i = 0; i < Tank.tanks.length; i++){
  if (Tank.tanks[i].id == 0){
     tank0Dead = false;
     break;
  }
}

https://jsfiddle.net/oqc5Lw73/5/

But I agree with @dimko1 about the idea of refactoring the code

Cyxo
  • 506
  • 3
  • 11
0

You can not break a forEach callback, simply because it's a function.

Here's updated working jSfiddle

If you really want to break it, you can use exception like code below.

try {
    [1,2,3].forEach(function () {
        if(conditionMet) {
            throw Error("breaking forEach");
        }
    });
} catch(e) {
}

Otherwise you can use jQuery's each() method. when it's callback returns false it stops.

jQuery.each([1,2,3], function () {
    if(conditionMet) {
        return false;
    }
});