简体   繁体   中英

Can I have a function name be an array variable?

Can I have a JavaScript loop like this?

SB = new Array;

for (i = 1; i < 6; i++) {

   function SB[i]() {

         (code)

   } // end of function

} // end of for loop

I know that doesn't work but how can I make something like that? Thanks.

Make an anonymous function and return it to the variable.

var SB = [];
for (i=1;i<6;i++) {
    SB[i] = function() {
        //(code)
    }
}

Note that arrays in javascript is 0-indexed.

So you fetch the first item in the array using

myArray[0]

And the last using

myArray[ myArray.length - 1 ]

So i think you want to loop with i=0 :

var SB = [];
for ( var i = 0; i < 5 ; i++) {
    SB[i] = function() {
        //(code)
    }
}

....

console.log(SB) // [function() {},function() {},function() {},function() {},function() {}]

Instead of:

[undefined, function() {}, function() {}, function() {}, function() {}, function() {}]
var SB=[];
for (i=1;i<6;i++) {
    SB[i] = function () {
        ...
    }
}

You can now invoke it this way:

SB[1]();

Use the bracket notation:

for ( var i = 1; i < 6; i++ ) {

    SB[i] = function() {

    };

}

This attaches a function expression to the array at index i . You are allowed to call it like this:

SB[ 1 ]();
SB[ 2 ]();

// etc..

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