开发者

Javascript invoking a function multiple times shorthand

开发者 https://www.devze.com 2023-03-16 06:58 出处:网络
I have been looking aro开发者_Python百科und for a while, and cant seem to find the answer for this.I do not know if it is possible, but am just curious.Suppose I have a simple function:

I have been looking aro开发者_Python百科und for a while, and cant seem to find the answer for this. I do not know if it is possible, but am just curious.


Suppose I have a simple function:

function foo(name){alert(name);}

Also suppose that I have to invoke this function several times with several different names:

foo("bar"); foo("blahh"); foo("myName"); foo("yourName");

Is there a shorthand for this?

For Example:foo("bar":"blahh":"myName":"yourName");

This example is trivial, but in practice that principal could be very useful. If there is some kind of jQuery solution I am open to that as well.


You could put your parameters in an array and iterate through it:

params = ["bar", "blahh", "myName", "yourName"];
for (var i=0; i<params.length; i++) 
    foo(params[i]);

If the func takes multiple args, you can put arrays in the arrays:

params = [[1,"one"], [2,"two"], [5,"five"]];
for (var i=0; i<params.length; i++) 
    foobar(params[i][0], params[i][1]);

or

params = [[1,"one"], [2,"two"], [5,"five"]];
for (var i=0; i<params.length; i++) 
    foobar.apply(null, params[i]);


As a generalization of other answers:

Function.prototype.sequence = function(vals) {
   for (var i = 0; i < vals.length; ++i) this(vals[i]);
}

this will add the sequence method to all functions. So you can use it with any function:

function foo() {....}

foo.sequence(["bar","blah","myName","yourName"]);


Think of the task as applying each element in a sequence, in turn, to the given function. In jQuery this can be done as:

function foo(name){ alert(name) }
$.each(["bar","blah","myName","yourName"], function (index, value) {
   foo(value)
})

The extra function is required because the jQuery.each callback is passed the index and value as parameters. It would be nice if the value was first :(

Compare with (a modified foo function):

function foo(index, name){ alert(name) }
$.each(["bar","blah","myName","yourName"], foo)

Happy coding.


You could pass an array to the function:

function foo(vals) {
   for (var i = 0; i < vals.length; ++i) {
       alert(vals[i]); 
   }
}

foo(["bar","blah","myName","yourName"]);


Actually you could do something like this:

function foo(){
for (var i=0; i< arguments.length; i++){
         alert(arguments[i]);
     }
}

and then you can call it with as many arguments you like:

foo('miao', 'baw');

//alerts miao and then baw

0

精彩评论

暂无评论...
验证码 换一张
取 消