Home >Web Front-end >JS Tutorial >Introduction to how to define functions in JavaScript
This article mainly introduces JavaScriptrelated information on defining functions. Friends who need it can refer to it
In JavaScript, the way to define functions is as follows:
function abs(x) { if (x >= 0) { return x; } else { return -x; } }
The above abs() function is defined as follows:
function indicates that this is a function definition;
abs is the name of the function;
(x) The parameters of the function are listed in brackets , multiple parameters are preceded by, Separation; The code between
conditional judgment and loops.
If there is no return statement, the result will be returned after the function is executed, but the result will be undefined. Since a JavaScript function is also an object, the abs() function defined above is actually a function object, and the function name abs can be regarded as a variable pointing to the function. So, the second way of defining a function is as follows:var abs = function (x) { if (x >= 0) { return x; } else { return -x; } };In this way, function (x) { ... } is a
Anonymous function, it has no function name. However, this anonymous function is assigned to the variable abs, so the function can be called through the variable abs.
The above two definitions are completely equivalent. Note that the second method requires adding a ; at the end of the function body according to the complete syntax, indicating the end of the assignment statement.Call the function
When calling the function, just pass in the parameters in order:
abs(10); // 返回10 abs(-9); // 返回9Since JavaScript allows any number of parameters to be passed in without affecting the call, there is no problem if more parameters are passed in than the defined parameters, although these parameters are not required inside the function:
abs(10, 'blablabla'); // 返回10 abs(-9, 'haha', 'hehe', null); // 返回9There is no problem if there are fewer parameters passed in than the ones defined:
abs(); // 返回NaNAt this time, the parameter x of the abs(x) function will receive undefined, evaluates to 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; } }
arguments
JavaScript also has a free keyword arguments, which only works inside the function and always points to all parameters passed in by the caller of the current function. arguments is similar to Array but it is not an Array:function foo(x) { alert(x); // 10 for (var i=0; i<arguments.length; i++) { alert(arguments[i]); // 10, 20, 30 } } foo(10, 20, 30);Using arguments, you can get all the parameters passed in by the caller. In other words, even if the function does not define any parameters, you can still get the value of the parameter:
function abs() { if (arguments.length === 0) { return 0; } var x = arguments[0]; return x >= 0 ? x : -x; } abs(); // 0 abs(10); // 10 abs(-9); // 9In fact, arguments are most commonly used to determine the number of parameters passed in. You may see writing like this:
// foo(a[, b], c) // 接收2~3个参数,b是可选参数,如果只传2个参数,b默认为null: function foo(a, b, c) { if (arguments.length === 2) { // 实际拿到的参数是a和b,c为undefined c = b; // 把b赋给c b = null; // b变为默认值 } // ... }To change the middle parameter b into an "optional" parameter, you can only judge it through arguments, and then readjust the parameters. and assign a value.
rest parameters
Since JavaScript functions allow receiving any number of parameters, we have to use arguments to obtain all parameters:function foo(a, b) { var i, rest = []; if (arguments.length > 2) { for (i = 2; i<arguments.length; i++) { rest.push(arguments[i]); } } console.log('a = ' + a); console.log('b = ' + b); console.log(rest); }In order to obtain parameters other than the defined parameters a and b, we have to use arguments, and the loop must start from index 2 to exclude the first two parameters. This way of writing is very awkward. , just to get extra rest parameters, is there a better way? The ES6 standard introduces the rest parameter. The above function can be rewritten as:
function foo(a, b, ...rest) { console.log('a = ' + a); console.log('b = ' + b); console.log(rest); } foo(1, 2, 3, 4, 5); // 结果: // a = 1 // b = 2 // Array [ 3, 4, 5 ] foo(1); // 结果: // a = 1 // b = undefined // Array []The rest parameter can only be If the parameters passed in are not filled with the normally defined parameters, it does not matter, the rest parameter will receive an empty array (note that it is not undefined). Because the rest parameter is a new ES6 standard, you need to test whether the browser supports it. Please write a sum() function using the rest parameter, which receives any number of parameters and returns their sum: Top of the form
'use strict'; // 测试: var i, args = []; for (i=1; i<=100; i++) { args.push(i); } if (sum() !== 0) { alert('测试失败: sum() = ' + sum()); } else if (sum(1) !== 1) { alert('测试失败: sum(1) = ' + sum(1)); } else if (sum(2, 3) !== 5) { alert('测试失败: sum(2, 3) = ' + sum(2, 3)); } else if (sum.apply(null, args) !== 5050) { alert('测试失败: sum(1, 2, 3, ..., 100) = ' + sum.apply(null, args)); } else { alert('测试通过!'); }
Be careful with your return statement
We mentioned earlier that the JavaScript engine has a mechanism to automatically add a semicolon at the end of the line, which may cause you to fall into a big pitfall with the return statement:function foo() { return { name: 'foo' }; } foo(); // { name: 'foo' }If you split the return statement into two lines:
function foo() { return { name: 'foo' }; } foo(); // undefinedBe careful, because the JavaScript engine With the mechanism of automatically adding a semicolon at the end of a line, the above code actually becomes:
function foo() { return; // 自动添加了分号,相当于return undefined; { name: 'foo' }; // 这行语句已经没法执行到了 }So the correct way to write multiple lines is:
function foo() { return { // 这里不会自动加分号,因为{表示语句尚未结束 name: 'foo' };
练习
定义一个计算圆面积的函数area_of_circle(),它有两个参数:
r: 表示圆的半径;
pi: 表示π的值,如果不传,则默认3.14
The above is the detailed content of Introduction to how to define functions in JavaScript. For more information, please follow other related articles on the PHP Chinese website!