What happens when I call a Javascript function which takes parameters, without supplying those parameters?

删除回忆录丶 提交于 2019-12-20 09:05:35

问题


What happens when I call a Javascript function which takes parameters, without supplying those parameters?


回答1:


Set to undefined. You don't get an exception. It can be a convenient method to make your function more versatile in certain situations. Undefined evaluates to false, so you can check whether or not a value was passed in.




回答2:


javascript will set any missing parameters to the value undefined.

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

fn(1); // outputs 1 on the console
fn(); // outputs undefined on the console

This works for any number of parameters.

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

also note that the arguments array will contain all arguments supplied, even if you supply more than are required by the function definition.




回答3:


There is the inverse to everyones answer in that you can call a function that doesnt appear to have parameters in the signature with parameters.

You can then access them using the built in arguments global. This is an array that you can get the details out of it.

e.g.

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)) 



回答4:


In addition to the comments above, the arguments array has zero length. One can examine it rather than the parameters named in the function signature.




回答5:


You get an exception as soon as you try to use one of the parameters.



来源:https://stackoverflow.com/questions/1846679/what-happens-when-i-call-a-javascript-function-which-takes-parameters-without-s

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!