|
|
|
|
|
by dragonwriter
1583 days ago
|
|
> ok, how do you implement a break of the iteration in map in JavaScript? If you want something that behaves like: array.map(x => {
if (x > 2) { break; } // can't really use break here!
else { return x; }
});
you do this: [...array].map((x,i,a) => {
if (x > 2) { a.splice(i); }
else { return x; }
});
(if you don’t need the array later, you can just use “array” instead of [...array]; the latter is just used because the break effect is achieved by mutating the array to delete all the elements subsequent to the one you are working, terminating the iteration, and copying the array initially means you don’t stomp the original.) |
|
so I guess I was wrong, you can get the same functionality of break in map, albeit in a way that, right at this moment, makes me uneasy.