user1282226
user1282226

Reputation:

Passing an argument into a FOR loop

I know I can simply write a while loop for this..

I'm just curious to know how to pass an argument like this:

   function i(a,z){

      for (a; a<2; z){

          //do something...

      }
   }

I tried

    i(0,a++);
    i(0,'a++');
    i(0,a=a+1);


    var z = "a= a+1";
    i(0,z);

and all didn't work.


​[UPDATE]

I know I can change the function into

   function i(a,z){

      for (a; a<2; a=a+z){

          //do something...

      }
   }

then

  i(0,1);

but what I want to know here is how I can pass that a=a+z as an argument without changing my function...

Upvotes: 0

Views: 84

Answers (3)

tuoxie007
tuoxie007

Reputation: 1236

function i(o){
    for (; o.a<2; o.z()){
        //do something...
        console.log('x');
    }
}
var o = {
    a:0, 
    z:function(o) {
        this.a++
    }
};

i(o);

Upvotes: 0

Samir Hafez
Samir Hafez

Reputation: 214

I'm not sure if I understand correctly but I guess you would want something like this:

function i(a, z){
    for (a; a < 2; a = z(a)){
        //do something...
    }
}

Then you call it like this:

i(0, function(a) { 
     a++; 
     return a;
});

Note that it is very similar to what you have except that the last part of the for is a function.

Upvotes: 0

Denis Ermolin
Denis Ermolin

Reputation: 5546

Maybe you want this variant?

function i(start, end, delta){

      for (var i = start; i<end; i += delta) {

          //do something...

      }
}

Use it i(0, 10, 1)

Upvotes: 4

Related Questions