[英]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 您正在寻找的是Array.prototype.concat
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat https://developer.mozilla.org/zh-CN/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.
您可以像在下面所示的问题中提到的那样创建自己的函数,或者像其他答案提到的那样使用CONCAT。 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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.