简体   繁体   中英

sending multiple parameters all in one call javascript

Let's say I'm trying to push multiple calls like:

var fields = [1,2];
fields.push(test("#test1", 1));
fields.push(test("#test2", 2));
fields.push(test("#test3", 3));
fields.push(newTest("#test5", 3, 'something'));

function test(a, b){
   // something here
}

function newTest(a, b, c){
   // something here
}

Is there an efficient way to do this all in one call? Like:

fields.push(test({"#test1": 1, "#test2": 2, "#test3": 3}), newTest(3, 4, "something"));

or

fields.push(test(["#test1": 1, "#test2": 2, "#test3": 3]), newTest(3, 4, "something"));

What you're looking for is Array.prototype.concat
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat

fields = fields.concat(
    test("#test1", 1),
    test("#test2", 2),
    test("#test3", 3),
    newTest("#test5", 3, 'something')
);

If the value is an array, the values of that array are pushed instead of the whole array. Other values are pushed directly.

There are several ways that you could add multiple values into an array with one command. You could create your own function as you mention in the question like shown below or use CONCAT like the other answer mentions. Here are two working examples that you can run to see how that works:

 //Original Array var fields = [1,2]; //Show original values console.log(fields); //Function call with multiple values test([3,4,5,6,7]); //Function to add each value sent to function in array function test(valueArray){ for (var i = 0; i < valueArray.length; i++) { var singleValue = valueArray[i]; fields.push(singleValue); } } //Show the result console.log(fields); //OR CONCAT TO DO THE SAME THING EASILY fields = [1,2];; fields = fields.concat(3,4,5,6,7); console.log(fields); 

You can do something like this if you want to add all at once:

var fields = [];

function test(a, b){
   return a+' '+b;
}

function newTest(a, b, c){
   return a+' '+b+' '+c;
}

fields.push(test("#test1",1),test("#test2",2),test("#test3",3),newTest("#newTest1",1,1));
console.log(fields);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM