1

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.

3 Answers 3

2

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() {}]
Sign up to request clarification or add additional context in comments.

Comments

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

You can now invoke it this way:

SB[1]();

Comments

0

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..

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.