D
D
dony322014-12-21 17:28:12
JavaScript
dony32, 2014-12-21 17:28:12

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]())
}

When the function is called, the entire list of the array is displayed on the console, but this is due to the redefinition of the identifier. Please tell me what needs to be done so that when 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

1 answer(s)
M
Mikhail Osher, 2014-12-21
@dony32

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 question

Ask a Question

731 491 924 answers to any question