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
Post a Comment