admin管理员组

文章数量:1352865

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);

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);
Share Improve this question edited May 23, 2015 at 15:05 gvlasov 20.1k22 gold badges83 silver badges119 bronze badges asked Jul 21, 2012 at 22:30 beatmusic67beatmusic67 353 bronze badges 3
  • Can you provide more context for your question? I can't figure out what exactly you need to happen. – jwatts1980 Commented Jul 21, 2012 at 22:35
  • What would you do in ActionScript? – tiwo Commented Jul 21, 2012 at 22:38
  • 1 No worries, there are no noob questions, just strange answers. ;) – Roko C. Buljan Commented Jul 21, 2012 at 22:58
Add a ment  | 

6 Answers 6

Reset to default 4

I'm not sure i understand the question, but how about

function blahBlah(n) {
    for(var i=0; i < n; i++) {
        //do something
    }
}
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

You mean calling the function each iteration?

function blahBlah( i ) {
    // do something with i
}

for ( var i = 0; i < 10; i++ ) {
    blahBlah( i );
}

Maybe like this:

function runLoop(length) {
    for (var i=0; i < length; i++) {
        {loop actions}
    }
}

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();
    }
}

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();

本文标签: javascriptpassing number to function for loop with jqueryStack Overflow