Answer the question
In order to leave comments, you need to log in
How to display the elements of a function / array of the form a[index]() without redefining the identifier?
var a = [1,2,3,77,5,6];
var b = [];
for (var i in a){
b.push(a[i]);
a[i] = function() {
return b[i];
}
}
for (var i in a){
console.log(a[i]())
}
console.log(a[3]())
(the construction must be of this type) 77 is displayed on the screen, and not the last element in the array?
Answer the question
In order to leave comments, you need to log in
The variable i is lost in the closure .
I'll try to describe in words.
In your case, at the time a[3]() is called , i has the last value in the loop.
Accordingly, I applied an IIFE to store the value of i by creating a new context.
DEMO
'use strict';
var a = [1,2,3,77,5,6];
var b = [];
for (var i in a) {
b.push(a[i]);
a[i] = (function(i) {
return function() {
return b[i];
};
})(i);
}
console.log(a[3]());
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question