Learner
Learner

Reputation: 21395

How to assign a function to a javascript variable

I have a requirement where I need to access an array element using its function.

For example, I have Array A[], now I want to create array B, such that

A[i] === B[i].value()

I tried below code but I am getting error as B[i].value is not a function

<script>
function test(A) {
    var B = new Array();
    for(var i=0; i<A.length; i++) {
        B[i] = function value() {
                return A[i];
            };
    }

    for(var i=0; i< B.length; i++) {
        console.log(B[i].value());
    }
    return B;
}

A=[1,2,3];
B = test(A);
</script>

What is the correct way for this?

Upvotes: 0

Views: 77

Answers (2)

Ele
Ele

Reputation: 33726

You need to assign an object instead:

B[i] = {
    value: function () {
        return A[i];
    }
}

To avoid any problems with the scope of i, you can use the statement let

The let statement declares a block scope local variable, optionally initializing it to a value.

function test(A) {
  var B = new Array();
  for (let i = 0; i < A.length; i++) {
    B[i] = {
      value: function() {
        return A[i];
      }
    };
  }

  for (let k = 0; k < B.length; k++) {
    console.log(B[k].value());
  }
  return B;
}

var B = test([1, 2, 3]);
console.log(B)
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 6

Code_Frank
Code_Frank

Reputation: 381

You could make value anonymous e.g. B[i] = function () { /* Your code */ } then just call B[i]() instead of B[i].value()

Upvotes: 1

Related Questions