2010-03-26 75 views

回答

32

JavaScript允许这样做,您可以将任意数量的参数传递给函数。

它们可以在arguments对象中访问,它是一个类似数组的对象,其数值属性包含调用该函数时使用的参数的值,该属性告诉您有多少参数已用于调用还和一个callee属性这对功能本身的引用,例如,你可以写:

function sum(/*arg1, arg2, ... , argN */) { // no arguments defined 
    var i, result = 0; 
    for (i = 0; i < arguments.length; i++) { 
    result += arguments[i]; 
    } 
    return result; 
} 
sum(1, 2, 3, 4); // 10 

arguments对象可能看起来像一个数组,但它是一个普通的对象,即从Object.prototype继承,但如果你想使用它的数组方法,你可以直接从调用它们,例如,一个常见的模式获得真正的数组是使用Array slice方法:

function test() { 
    var args = Array.prototype.slice.call(arguments); 
    return args.join(" "); 
} 
test("hello", "world"); // "hello world" 

此外,你可以知道一个函数多少个参数预计,使用的的length财产函数对象:

function test (one, two, three) { 
    // ... 
} 
test.length; // 3 
+0

你可以叫'test.lengt函数内的h''来测试用户输入的参数数量? – 2016-10-27 01:46:40

+0

或可以使用'[] .slice.call(参数);' – Mahi 2016-11-18 06:18:57

4

是做到这一点 - 它的很好的做法,是一个强大的JavaScript功能