5 ms·
for(var i in list) { (function(element) { someAsyncCallThatNeedsTheRightIndexedElement(element); })(list[i]); } I've seen people grumble that
by emblem21 10y ago
for(var i in list) {
(function(element) {
someAsyncCallThatNeedsTheRightIndexedElement(element);
})(list[i]);
}
I've seen people grumble that this is "too clever"
I've been known to snap back "Bootcamps don't have a monopoly on what technical solutions are valid"
Pointers are probably too clever for most people.
Admittedly, goto is too clever for me. :(
- atoko 10y agoTry using .call
- Jach 10y agoWhen "too clever" is "I don't understand", yeah, it's bad. I'd snap back with "let's use clojurescript then". Or I'll clarify whether they think 'var i' in the loop is too clever or the scope fixing code that's pretty common to do in JS is too clever.
- olalonde 10y agoI'd just write: for(var i in list) { someAsyncCallThatNeedsTheRightIndexedElement(list[i]) } though I usually try to avoid for loops with `.map` or `.forEach`: list.forEach(someAsyncCallThatNeedsTheRightIndexedElement) The IIFE in your code is unnecessary and I would thus probably side with the too clever camp in this case.
- Strilanc 10y agoNote: this is fixed in ES6. Using `let` instead of `var` will treat each iteration's variable as distinct: a = [] for (let i = 0; i <3; i++) a.push(() => console.log('hi ' + i)) for (let e of a) e() Logs: hi 0 hi 1 hi 2 Actually, it's almost surprising in the opposite direction now.