Home > Web Front-end > JS Tutorial > Let's talk about the definition and basic use of JavaScript functions

Let's talk about the definition and basic use of JavaScript functions

WBOY
Release: 2022-07-01 11:59:04
forward
2006 people have browsed it

This article brings you relevant knowledge about javascript, which mainly organizes issues related to the definition and basic use of functions, including definitions with function statements, function calls, and undefined Let’s take a look at the actual parameters and so on. I hope it will be helpful to everyone.

Let's talk about the definition and basic use of JavaScript functions

[Related recommendations: javascript video tutorial, web front-end

1. Define with function statements

Let’s give an example first. The function of this function is to return the sum of array elements;

function sumArray(arr) {  
    var sum = 0;  
    for(var i = 0,aLength = arr.length;i < aLength;i++) {  
        sum += arr[i];  
    }  
    return sum;  }
Copy after login

Keyword functionThere is a space after it, sumArray is the name of the function, and its naming convention is the same as that of variable names: can only contain letters, numbers, underscores, and dollar signs, and cannot start with a number or be a keyword.

The parameters in brackets are also called formal parameters. Only the parameter name is required. Parameters can be 0, 1 or more, separated by , , {} is included in the middle Function body. Contains one or more statements. The function body is used to implement the function of the function.

Keywordreturn is followed by the return value of the function. The function can also have no return value. After the function is finished running, return this sentence will exit the operation, returnThe following statement will no longer run. The return value is the output of the function.

For a function defined in this way, the function can be called both before and after the function definition, as long as the function and the statement calling the function are in the same source file.

2. Use expression definition

Define a function in the form of an expression, which is to use an assignment expression to assign the function to a variable . This is actually to see the function as into a variable. At this time, the function can have a name or no name. The function without a name is called anonymous function.

  • With name;
var funct = function getMax(a,b) {  
    return a>b?a:b;  };//注意这后面的分号不能少,因为我们定义的是一个变量!
Copy after login

and are defined with function statementsThe difference is that they can only be defined after the function definition statementCall this function, and when calling, you can only use the variable name funct, but not the function name getMax, such as:

var funct = function getMax(a,b) {  
    return a>b?a:b;  
};  
console.log(funct(1,2));//输出2
Copy after login
  • Anonymous function;
    The so-called anonymous function is the keyword function followed directly by the parameter list:
var funct = function(a,b) {  
    return a>b?a:b;  };
Copy after login

This function has no name, it is assigned to the variablefunct, so it is called an anonymous function. Similarly, can only call this function after this statement.

var funct = function(a,b) {  
    return a>b?a:b;  };  console.log(funct(1,2));//输出2
Copy after login

Summary: Defining a function with an expression is ready for use. Once defined, the function can only be called after this statement

3 .Function calling

In the fourth training, we once introduced that objects can have their own methods, and of course these are also functions. The call of this function is slightly different from the functions defined in the previous two levels.

//函数的定义:求三个数的最大值  
function max(a,b,c) {  
    if(a > b) {  
        if(a > c)  
            return a;  
        else   
            return c;  
    }  
    else {  
        if(b > c)  
            return b;  
        else   
            return c;  
    }  
}  
//调用该函数  
var result = max(1,2,3);//result为3  
console.log(result);//输出3
Copy after login

When calling a function, you need to pass in the same number of specific values ​​as the formal parameters. The above function has 3 parameters, so when calling the following, pass in 3 specific values, 1 is passed to parameter a, 2 is passed to parameter b, 3 Pass parameter c. The return value of the function is passed to the variable result through the assignment symbol =. If there is no return keyword in the function body, undefined will be returned.

Call the function defined in the object:

var ob = {  
    id:1,  
    getMax:function(a,b) {  
        return a>b?a:b;  
    }  };  var result = ob.getMax(2,1);//result值为2  var result1 = ob["getMax"](2,1);//result1的值也是2
Copy after login

The difference from the above is that to locate the function here, you need to use the object name. Function name or Object name ["function name"], the others are the same.

4. Undefined actual parameters

In most programming languages, the number and type of actual parameters passed in when calling a function will be checked, and JavaScriptBoth does not check the type of actual parameters, nor does it check the number of actual parameters. The actual parameters in
JavaScript will match the formal parameters in order from left to right, for example:

function myFunction(a,b,c) {  
    console.log(a);  
    console.log(b);  
    console.log(c);  }  myFunction(1,2,3);
Copy after login

actual parameters1Incoming formal parameters a, actual parameters 2 Incoming formal parameters b, Incoming actual parameters 3 Incoming formal parameters c. When the number of actual parameters is less than the formal parameters, the value undefined will be passed to the right formal parameter. For example:

function myFunction(a,b,c) {  
    console.log(a);  
    console.log(b);  
    console.log(c);  }  myFunction(1,2);
Copy after login

actual parameter1pass in formal parametera,actual parameter2pass in formal parameterb,undefinedIncoming formal parametersc. If you only want to pass data to the parameters on the right, you can pass undefined to the first few actual parameters. For example:

function myFunction(a,b,c){  console.log(a);  console.log(b);  console.log(c);  }  myFunction(undefined,1,2);
Copy after login

The above two methods are not rigorous enough. The best practice is to set a default value for formal parameters that may be passed in an undefined value. like:

function getSum(a,b,c) {  
    if(c === undefined)   
        c = 0;  
    console.log(a+b+c);  }  myFunction(1,2);
Copy after login

5.实参对象

JavaScript一切都是对象,实参也是一个对象,有一个专门的名字arguments,这个对象可以看成一个数组(类数组,不是真的数组),实参从左到右分别是arguments[0]、arguments[1]...arguments.length表示实参的个数。

//求参数的和  function getSum() {  
    var aLength = arguments.length;  
    var sum = 0;  
    for(var i = 0;i < aLength;i++) {  
        sum += arguments[i];  
    }  
    return sum;  }  console.log(getSum(1,2,3,4,5))//输出15
Copy after login

这里的形参直接省略,使用arguments[i]表示。

6.对象作为参数

复杂的函数通常多达十几个参数,尽管JavaScript不做参数个数和类型的检查,但是调用时实参的顺序不能乱。开发人员需要检查每一个实参和形参的对应关系,这样效率很低。一种很好的解决方案是使用对象作为参数,函数会根据对象的属性名操作参数。

function myFunction(obj) {  
    console.log(obj.name);  
    obj.number++;  
    return obj.number;  }  myObj = {name:"myObj",number:34};  myFunction(myObj);//输出myObj  console.log(myObj.number);//输出35
Copy after login

7.函数对象作为另一个函数的参数

一个函数(为方便行文,称为a函数)可以作为另外一个函数(称为b函数)的参数b函数最终可以返回一个具体的值。

从原理上来说,b函数在自己的函数体内调用了a函数,所以需要把a函数的名字作为实际参数传递给b函数。如下:

//求最大值  function getMax(a,b) {  
    return a>b?a:b;  }  //求最小值  function getMin(a,b) {  
    return a<b?a:b;  }  //下面这个函数以函数作为参数,并最终返回一个值  function getM(func,num1,num2) {  
    return func(num1,num2);  }  getM(getMax,1,2);//返回2  getM(getMin,1,2);//返回1
Copy after login

我们把a函数的名字(getMax或者getMin)传给b函数(getM()),然后在b函数内部调用传入的a函数,得到相关的结果。

【相关推荐:javascript视频教程web前端

The above is the detailed content of Let's talk about the definition and basic use of JavaScript functions. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template