0

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?

2
  • 1
    A[i] === B[i].value() - there is smth wrong Commented Mar 21, 2018 at 20:21
  • The (optional) name of a function expression is only available within the function, it doesn't create a named property of the object it's assigned to. Commented Mar 21, 2018 at 20:24

2 Answers 2

6

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; }

Sign up to request clarification or add additional context in comments.

8 Comments

Thanks Ele, Is there any other way to add this function?
closures people! Change the second counter to j. Six votes - amusing!
Yes, If I use` j` in my second loop instead of i, it did not work, got error
@Igor six votes because the OP wants to call the function as follow B[index].value(). Of course, you're right about the scope problem. See the updated answer!
@Ele OP also wants B[i].value === B[j].value. OP does not know what they want.
|
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.