简体   繁体   中英

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?

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

您可以将值匿名化,例如B[i] = function () { /* Your code */ }然后只需调用B[i]()而不是B[i].value()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM