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.

David G
97.6k41 gold badges173 silver badges258 bronze badges
asked Nov 18, 2012 at 13:09

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() {}]
answered Nov 18, 2012 at 13:10
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]();
answered Nov 18, 2012 at 13:10

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..
answered Nov 18, 2012 at 13:10

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.