javascript - Stop passing by reference in closures -


this question has answer here:

i have code looks this:

var = []; for(var = 0; < 10; i++) {     a[i] = function() {         console.log(i);     } } 

unfortunately, seems i being passed reference, functions in a output 10. how make each function outputs value i had when created? i.e. a[0]() gives 0, a[1]() gives 1, etc.

edit: clarify, not want a store values 0-9. want a store functions return values 0-9.

you need invoke function (to create closure captures value) returns function (the 1 want end with). this:

var = []; (var = 0; < 10; i++) {     a[i] = (function(value) {         return function() {             console.log(value);         }     })(i); } 

Comments

Popular posts from this blog

java - UnknownEntityTypeException: Unable to locate persister (Hibernate 5.0) -

python - ValueError: empty vocabulary; perhaps the documents only contain stop words -

ubuntu - collect2: fatal error: ld terminated with signal 9 [Killed] -