2014-01-14 113 views
12

知道,如果我的功能需要增值税吗?是否可以确定函数是否有参数?

例如:

function ada (v) {}; 
function dad() {}; 
alert(ada.hasArguments()); // true 
alert(dad.hasArguments()); // false 
+0

也称为[所述元数](https://en.wikipedia.org/wiki/Arity):) – Andy

回答

17

是。函数的length属性返回声明的参数个数:

alert(ada.length); // 1 
alert(dad.length); // 0 
+0

能够以动态语言查找函数的已声明参数的数目非常有用,但JavaScript决定将此属性称为“长度”似乎很奇怪...... – iamnotmaynard

+2

它真的有用吗? –

4

功能的length属性表示形式参数的数量。注意,这并不一定等于实际参数的数目:

function foo(one, two, three) { 
    return foo.length === arguments.length; 
} 

foo("test"); 
foo("test", "test", "test"); 

输出:

false 
true 
+0

+1使用正确的术语“形式参数”,尽管它应该读作“......不一定等于实际*参数数量”。 –

+0

“实际参数”是多余的。 “参数”和“实际参数”是同义词。 –

+0

请参阅:http://en.wikipedia.org/wiki/Parameter_(computer_programming)#Parameters_and_arguments –

相关问题