0

so i have a homework problem need to solve . The requirement is just fix the code so console show true

 var x = 2,
 fns = [];

(function () {
  var x = 5;

  for (var i = 0; i < x; i++) {
  //  write here 
  }
})();

// DO NOT MODIFY BELOW CODE
console.log(x * 2===fns[x * 2]());
// console must show true

the console output is

Uncaught TypeError: fns[(x * 2)] is not a function

I try to rewrite function as it one of element in array but console still show error. I rewrite the fns[x * 2]() to fns[x * 2] and the console show return false (which is fine cause at least it not throw error ) but cant modify it according to the requirement

phuonglinh
  • 23
  • 4

2 Answers2

1

Each element of the array needs to be a function that returns its current index in the array:

var x = 2,
  fns = [];

(function() {
  var x = 5;

  for (let i = 0; i < x; i++) {
    fns[i] = () => i;
  }
})();

// DO NOT MODIFY BELOW CODE
console.log(x * 2 === fns[x * 2]());
// console must show true

Make sure to declare the index variable with let, not var (var has problems).

Or, more functionally:

const fns = Array.from(
  { length: 5 },
  (_, i) => () => i
);

let x = 2;
// DO NOT MODIFY BELOW CODE
console.log(x * 2 === fns[x * 2]());
// console must show true
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
0

You need a closure with an IIFE which takes the value.

var x = 2,
    fns = [];

(function() {
    var x = 5;

    for (var i = 0; i < x; i++) {
        fns[i] = function (v) {
            return function () { return v; };
        }(i);
    }
})();

// DO NOT MODIFY BELOW CODE
console.log(x * 2 === fns[x * 2]());
// console must show true
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392