The previous article describes some methods of objects and arrays in js. In this chapter, let's talk about functions first, and then perform some practical operations. 1. function:
Function is a js Code that is defined once but can be called multiple times.
When a function is called by an object, this function is called the object method.
function cssrain( x , y) { //code }
Explanation:
Cssrain: The function name;
(): Operator;
X, y: the parameter;
2. function return value:
Function a (x) {document. write (x);} function B (y) {document. write (y); return y;} alert (a (1) // returns undefined alert (B (2) because no return is written ))
3. function statement and function quantity:
function f(x) { return x * x ;} // var f = function(x){ return x * x ;} //
The first is the function statement, and the second is to define an expression directly using the function. Of course, this method is used to create an anonymous function.
Although the direct quantity can be anonymous, you can also specify the function name;
For example:
Var f = function fact (x) {return x * fact (x-1);} // the benefit of doing so; the call itself is very nice.
4. Function Name:
Function like_this (){}
Or function likeThis () {}// camper
5. function parameters:
Because Javascript is a loose type language, you do not need to specify any data types for parameters. Parameters can be more or less,
For example: function x (a, B) {}// we wrote two parameters.
If we pass three parameters, js will automatically ignore multiple/
Instance:
function x(a,b){ document.write(a+ " "+b); } x(1,2,3,4);
What happens if we pass only one parameter?
function x(a,b){ document.write(a+ " "+b); } x(1);
We found that undefined is output, so js will assign less to undefined;
This may cause program errors.
Solution:
Function x (a, B) {var B = B | ""; // This is an OR operator. If B is undefined, it is false, it will take the blank character document. write (a + "" + B);} x (1 );