简体   繁体   English

如何将函数分配给javascript变量

[英]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 [],现在我想创建数组B,这样

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

I tried below code but I am getting error as B[i].value is not a function 我尝试了下面的代码,但由于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 为了避免i的范围出现任何问题,可以使用语句let

The let statement declares a block scope local variable, optionally initializing it to a value. let语句声明一个块作用域局部变量,可以选择将其初始化为一个值。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在javascript中为返回函数的变量赋值 - how to assign a value to a variable of a return function in javascript 如何在JavaScript中将箭头函数(=&gt;)的结果分配给变量 - How to assign a result of an arrow function (=>) to a variable in JavaScript 如何将JavaScript函数中的变量值分配给Mason变量? - How to assign the value of the variable in JavaScript function into a Mason variable? 如何将php变量传递给ajax成功函数并分配给JavaScript变量 - how to pass php variable in to ajax success function and assign in to JavaScript variable Javascript:如何分配变量? - Javascript: How to assign to a variable? 如何将javascript事件函数的返回值分配给javascript变量 - how to assign return value of a javascript event function to a javascript variable 将Razor函数分配给JavaScript变量? - Assign a Razor Function to a JavaScript Variable? 将函数分配给javascript中的全局变量 - assign a function to a global variable in javascript 如何在JavaScript中的回调函数中的回调函数中分配变量 - How to assign a variable in callback function in a callback function in javascript Javascript-尝试将函数分配给变量 - Javascript - Trying to assign a function to a variable
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM