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
3 Answers 3
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
Andreas Louv
47.3k14 gold badges109 silver badges126 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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
user1726343
Comments
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
David G
97.6k41 gold badges173 silver badges258 bronze badges
Comments
lang-js