5 ms·
I feel bad, because as I was writing a solution to this I knew why it wouldn't work and why (returning my counter variable returns the value at the end of the c
by speg 12y ago
I feel bad, because as I was writing a solution to this I knew why it wouldn't work and why (returning my counter variable returns the value at the end of the count) but I still couldn't come up with a fix :(
Edit: A good Google seems to suggest using JSON.stringify and JSON.parse to copy the value.
Edit 2: But even that doesn't seem to work :(
Edit 3: Got it, using a generator function. Which makes sense. I guess I'm not an expert yet! :)
- tcqag 12y agoHere's a solution using closure: http://codepen.io/anon/pen/KwmQam http://codepen.io/anon/pen/KwmQam
- b3tta 12y agoUsing a closure: function foo(s) { function generator(i) { return function () { return i; }; } var r = new Array(s); for (var i = 0; i < s; i++) { r[i] = generator(i); } return r; } console.log(foo(1000)[42]()); Using Function.prototype.bind(): function foo(s) { function generator(i) { return i; } var r = new Array(s); for (var i = 0; i < s; i++) { r[i] = generator.bind(window, i); } return r; } console.log(foo(1000)[42]());
- deleted 12y ago[deleted]