当我调用带有参数的Javascript函数而不提供这些参数时会发生什么?

Kru*_*elz 38 javascript parameters

当我调用带有参数的Javascript函数而不提供这些参数时会发生什么?

KP.*_*KP. 37

设置为undefined.你不会得到例外.它可以是一种方便的方法,使您的功能在某些情况下更通用.未定义的计算结果为false,因此您可以检查是否传入了值.

  • 此外,您可以提供比函数接受的*更多*参数.然后,您可以通过`arguments`集合访问所有参数.`function test(param1){alert(param1); if(arguments.length == 2)alert(arguments [1]); } test(); 试验(1); 试验(1,2);` (7认同)
  • 如果您的函数可以接受五个参数,而您只提供两个参数,该怎么办?一样? (2认同)

bar*_*ley 16

javascript会将任何缺少的参数设置为该值undefined.

function fn(a) {
    console.log(a);
}

fn(1); // outputs 1 on the console
fn(); // outputs undefined on the console
Run Code Online (Sandbox Code Playgroud)

这适用于任意数量的参数.

function example(a,b,c) {
    console.log(a);
    console.log(b);
    console.log(c);
}

example(1,2,3); //outputs 1 then 2 then 3 to the console
example(1,2); //outputs 1 then 2 then undefined to the console
example(1); //outputs 1 then undefined then undefined to the console
example(); //outputs undefined then undefined then undefined to the console
Run Code Online (Sandbox Code Playgroud)

另请注意arguments,即使您提供的函数超出了函数定义所需的数量,该数组也将包含所有提供的参数.


Aut*_*ter 8

与每个人的答案相反,您可以调用一个函数,该函数似乎没有带参数的签名中的参数.

然后,您可以使用内置arguments全局访问它们.这是一个数组,您可以从中获取详细信息.

例如

function calcAverage() 
{ 
   var sum = 0 
   for(var i=0; i<arguments.length; i++) 
      sum = sum + arguments[i] 
   var average = sum/arguments.length 
   return average 
} 
document.write("Average = " + calcAverage(400, 600, 83)) 
Run Code Online (Sandbox Code Playgroud)