arrays - Preferred way to break a forEach method in JavaScript -


this question has answer here:

i using foreach method in javascript sum elements in array. felt need break out of loop on conditions, example putting limit on sum calculated. have come following solution. point me if wrong.

small edit this

function foreach(a) {  var sum = 0;  var breakexception = {error:"stop it"};  try {     a.foreach(function (v) {         sum += v;         console.log(sum);         if(sum>5) throw breakexception.error;     });     return sum; } catch(e) {     if(e!=breakexception){         throw e;     } } } 

foreach not supposed break. if 'd break foreach-like loop, try every or some, let break out of loop.

a possible way re-write code be

var sum = 0;  yourarray.some(function (item) {     if (sum > 5) {         return true;     }     sum += item; }); 

Comments

Popular posts from this blog

google chrome - Developer tools - How to inspect the elements which are added momentarily (by JQuery)? -

angularjs - Showing an empty as first option in select tag -

php - Cloud9 cloud IDE and CakePHP -