Javascript:将多个参数作为单个变量传递

use*_*797 7 javascript argument-passing

是否可以使用单个变量传递多个参数?例如,如果我想做类似的事情:

function foo(x,y){
    document.write("X is " + x);
    document.write("Y is " + y);
}

var bar = "0,10";
foo(bar);
Run Code Online (Sandbox Code Playgroud)

上面的例子是我试图做的简化示例.它不起作用(因为"bar"被检测为单个参数).我知道有更简单的方法可以使用数组来实现它.

所以,我主要是出于好奇而问这个问题 - 是否有可能将"bar"变量检测为不是一个,而是两个参数?

谢谢!

jtb*_*des 13

function foo(thing) {
    document.write("X is " + thing.x);
    document.write("Y is " + thing.y);
}

var bar = {x:0, y:10};
foo(bar);
Run Code Online (Sandbox Code Playgroud)


Top*_*era 0

你可以使用这个:

var bar = [0,10]; // creates an array
foo(bar);

function foo(arg){
    document.write("X is " + arg[0]);
    document.write("Y is " + arg[1]);
}
Run Code Online (Sandbox Code Playgroud)