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() {}]