A function is a piece of code that is combined to perform a specific task. Functions generally use parameters to interact with the outside world. To write concise and efficient JS code, you must master function parameters.
In this article, some interesting examples will be used to explain all the features that JS has to handle function parameters efficiently.
1. Function parameters
function sum(param1, param2) { console.log(param1); // 1 console.log(param2); // undefinedreturn param1 + param2; } sum(1); // NaN
The number of parameters passed in during the call should be the same as the number of parameters defined in the function. Of course, the number of parameters passed in is less than the number of parameters defined in the function. Sometimes, no error will be reported, and undefined will be used instead.
2. Default parameters
function sum(param1, param2 = 0) { console.log(param2); // 0 return param1 + param2; } sum(1); // 1 sum(1, undefined); // 1
If the second parameter is not passed in, param2 will default to 0.
Note that if undefined is set to the second parameter sum(1, undefined), param2 will also be initialized to 0.
3. Destructuring parameters
functiongreet({ name }) { return`Hello, ${name}!`; } const person = { name: '前端' }; greet(person); // 'Hello, 前端'
4. arguments object
JavaScript function has a built-in object arguments object. The argument object contains the argument array for the function call. In this way you can easily find the largest parameter value
x = findMax(1, 123, 500, 115, 44, 88); function findMax() { var i, max = arguments[0]; if(arguments.length < 2) return max; for (i = 0; i < arguments.length; i++) { if (arguments[i] > max) { max = arguments[i]; } } return max;}
5. The remaining parameters
will be an indefinite number of The parameters are represented as an array
function sumArgs() { console.log(arguments); // { 0: 5, 1: 6, length: 2 } let sum = 0; for (let i = 0; i < arguments.length; i++) { sum += arguments[i]; } return sum; } sumArgs(5, 6); // => 11
Recommended: "2021 js interview questions and answers (large summary)"
The above is the detailed content of Several parameter forms in JS functions. For more information, please follow other related articles on the PHP Chinese website!