Reputation: 35
I was wondering how to pass a number to a function I created for a loop. For example, I have a loop that simply adds 1 to a value when it runs. How would I go about passing how many times I want the loop to run in a function? Like so:
var i = 0;
function blahBlah (i ?){
for (i=0,i>10(this is what I want to pass to the function),i++){
i++;
}
Then call the function:
blahBlah(number of times I want it to run);
Upvotes: 2
Views: 2422
Reputation: 15566
function blahBlah (noOfTimes){
for (var i=0 ;i < noOfTimes ;i++){
//i++; you already incremented i in for loop
console.log(i);//alert(i);
}
}
blahBlah(10);// call function with a loop that will iterate 10 times
Upvotes: 2
Reputation: 3369
Use a loop inside your function:
function BlahBlah(n) {
for (i=0; i < n; ++i) {
// do something...
}
}
or simply invoke the function in a for loop:
function Blahblah() { /* do something */ }
// elsewhere:
n = 42;
for (i=0; i < n; ++i) BlahBlah();
Upvotes: 1
Reputation: 20035
First, you used , instead of ; in for loop.
Second, you need two variables here: the first one is how many times to repeat (i
, the argument), the second is a counter (a
, which iteration is it now)
function blah(i) {
for (var a=0; a<i; a++) {
doStuff();
}
}
Upvotes: 1
Reputation: 7356
Maybe like this:
function runLoop(length) {
for (var i=0; i < length; i++) {
{loop actions}
}
}
Upvotes: 2
Reputation: 7590
I'm not sure i understand the question, but how about
function blahBlah(n) {
for(var i=0; i < n; i++) {
//do something
}
}
Upvotes: 4
Reputation: 20235
You mean calling the function each iteration?
function blahBlah( i ) {
// do something with i
}
for ( var i = 0; i < 10; i++ ) {
blahBlah( i );
}
Upvotes: 2