Calling the function
When calling the function, just pass in the parameters in order:
abs(10); / / Return 10
abs(-9); // Return 9
Since JavaScript allows any number of parameters to be passed in without affecting the call, pass in There is no problem if there are more parameters than the defined parameters, although these parameters are not required inside the function:
abs(10, 'blablabla'); // Return 10
abs(-9, 'haha', 'hehe', null); // Return 9
There is no problem if you pass in fewer parameters than defined:
abs(); // Return NaN
At this time, the parameter x of the abs(x) function will receive undefined, and the calculation result is NaN.
To avoid receiving undefined, you can check the parameters:
function abs(x) { if (typeof x !== 'number') { throw 'Not a number'; } if (x >= 0) { return x; } else { return -x; } }
The following case carefully observes how to use the function call
<!DOCTYPE html> <html> <body> <p>点击这个按钮,来调用带参数的函数。</p> <button onclick="myFunction('学生','XXX')">点击这里</button> <script> function myFunction(name,job) { alert("Welcome " + name + "," + job); } </script> </body> </html>