是否可以使用单个变量传递多个参数?例如,如果我想做类似的事情:
function foo(x,y){
document.write("X is " + x);
document.write("Y is " + y);
}
var bar = "0,10";
foo(bar);
上面的例子是我想要做的事情的简化例子。 它不起作用(因为“bar”被检测为单个参数)。 我知道有更简单的方法可以使用数组来实现这一点。
所以,我问这个问题主要是出于好奇 - 是否有可能将“bar”变量检测为不是一个参数,而是两个参数?
谢谢!
function foo(thing) {
document.write("X is " + thing.x);
document.write("Y is " + thing.y);
}
var bar = {x:0, y:10};
foo(bar);
你所要求的是不可能的。如果要在单个参数中传递多个值,请使用
Array
或 Object
。如果您确实必须使用字符串,则必须调用split()
将参数字符串分解为数组。
function Add (a, b, c) {
return a + b + c;
}
var nums = [1, 2, 4];
var sum = Add.apply (null, nums);
可变长度参数列表:
function Add () {
var sum = 0;
for (var i = 0; i < arguments.length; i++) {
sum += arguments[i];
}
return sum;
}
var n = Add (1, 2, 3, 4, 5);
当然,传递选项对象是很常见的
function foo(options){
//...
}
然后你可以传入任何东西...
var opts = {};//create an object
opts['x'] = 5;//set whatever properties you want
opts['y'] = 23;
opts['border'] = 3;
foo(opts);//pass 1 argument, with as many values as you want
这些通常是内联定义的,尤其是在方法调用之外不需要这些值的情况下。
foo({'x':5,'y':23,'border':3});
其实不然。
你可以这样做:
window.foo.apply(window, bar.split(','));
(Apply 允许您传递参数数组,而不是单独传递每个参数)
…但是我想到了“丑陋”这个词。
您可以使用这个:
var bar = [0,10]; // creates an array
foo(bar);
function foo(arg){
document.write("X is " + arg[0]);
document.write("Y is " + arg[1]);
}
不,但您可以传递数组或对象:
function foo(options){
document.write("X is " + options.x);
document.write("Y is " + options.y);
}
var bar = {x: 0, y:10};
不,这是不可能的。您可以将两个参数放入一个数组中,但数组仍然是一个变量。然后,您需要重写该函数以接受一个变量,并将其视为一个数组,如下所示:
function foo(x){
document.write("X is " + x[0]);
document.write("Y is " + x[1]);
}
基本上,函数接受变量作为参数,并且无论您传递哪种变量,每个变量仍然只是一个变量 - 没有办法将单个变量识别为多个参数。数组是一个变量,JSON 对象是一个变量,等等。这些东西有多个部分,但它们被单个变量封装。
怎么样? (适用于 ES6+)
function foo({x, y}){
document.write("X is " + x);
document.write("Y is " + y);
}
并用以下方式调用它:
foo({x:10, y:5})
在多个参数上使用单个结构化参数有一个缺点,即对于多个参数,您可以在多种 IDE 中使用
/**
来生成方法头,该头将为每个参数显示 @param
。
但是,如果您只有一个参数,那么您将失去每个参数的描述的准确性,因此 IDE 中的智能感知不太有用,因为它不会获取结构属性的文档。
/**
* Do stuff
* @param {*} param0 - A structure containing the blah, blah blah data
*/
function foo({x, y}){
而不是..
/**
*
* @param {*} x - The value for blah
* @param {*} y - the value for blah-blah
*/
foo1(x, y){
这是一个老问题,但我今天正在寻找答案,没有在这里找到它,我自己想出来了所以发帖。在现代 JS 中,您可以使用扩展语法来实现您的目标。文档中的示例:
function sum(x, y, z) {
return x + y + z;
}
const numbers = [1, 2, 3];
console.log(sum(...numbers));
// Expected output: 6
你的例子:
function foo(x,y){
document.write("X is " + x);
document.write("Y is " + y);
}
var bar = [0, 10];
foo(...bar);
使用 .apply() 的方法也有效,但据我了解,扩展语法更现代,看起来更简洁。
直接回答你的问题,不。值得注意的是,您定义
bar
的方式只是一个值,一个包含“0,10”的字符串。
function myFunction(a,b){
//do stuff with a and b here
}
myFunction(1,'text')
或者...
<a onClick="myFunction(1,'text');"
有一篇关于这个问题的文章这里。