3 ms·
Here's what I'd do: array = []; function clos(val) { return () => val; } for (var i = 0; i < 10; i++) { array.push(clos(i)); } array.forEach(fn
by cess11 2y ago
Here's what I'd do:
array = [];
function clos(val) { return () => val; }
for (var i = 0; i < 10; i++) { array.push(clos(i)); }
array.forEach(fn => console.log(fn()));
This outputs 0-9 instead of 10, though I'm just a silly self-taught person that never got schooled at these things, maybe there is some reason not to use closures that I don't know about.
- ifwinterco 2y agoThese days in JS you can just use let instead of var and it will work, but in itself that inconsistency is a bit weird
- cess11 2y agoYeah, let/const is what I tend to use. Here I wanted to change someone else's code as little as possible. Edit: Oh, right, it also solves the 10-issue. Thanks, didn't realise at first.