(JavaScript learning record): function

table of Contents

Function concept

Use of functions

Declare function

Call functions

Function encapsulation

Function parameters

Formal and actual parameters

The passing process of function parameters

The problem of the number of function parameters and actual parameters does not match

summary

The return value of the function

return statement

return termination function

return value

Function without return returns undefined

The difference between break, continue, return

See through the function through the juicer

Use of arguments

Function case

Function can call another function

Two ways of function declaration

Custom function method (named function)

Function expression mode (anonymous function)


Function concept

  • Function : It encapsulates a code block that can be repeatedly called and executed . Through this code block, a large amount of code can be reused.

Use of functions

  • There are two steps when a function is used: declaring the function and calling the function .

Declare function

// 声明函数
function 函数名() {
 //函数体代码
}
  • function is a keyword for declaring functions and must be lowercase
  • Since functions are generally defined to achieve a certain function, we usually name the function name as a verb , such as getSum

Call functions

// 调用函数
函数名(); // 通过调用函数名来执行函数体代码
  • Don't forget to add parentheses when calling
  • Mantra: The function does not call and does not execute itself .
  • Note: Declaring the function itself does not execute the code, the function body code is executed only when the function is called.

Function encapsulation

  • Function encapsulation is to encapsulate one or more functions through functions , and only provide a simple function interface to the outside
  • Case: Use a function to calculate the cumulative sum between 1-100
/* 
 计算1-100之间值的函数
*/
// 声明函数
function getSum(){
 var sumNum = 0;// 准备一个变量,保存数字和
 for (var i = 1; i <= 100; i++) {
 sumNum += i;// 把每个数值 都累加 到变量中
 }
 alert(sumNum);
}
// 调用函数
getSum();

Function parameters

Formal and actual parameters

  • In the function declaration , may be added in parentheses following the name of the function parameters, these parameters are referred to as parameter , while the function is called , also need to pass the appropriate parameters, these parameters are referred to arguments .

  • The role of parameters : Some values within the function cannot be fixed, we can pass different values ​​in when calling the function through the parameters .
  • When declaring a function , you can add some parameters in parentheses after the function name. These parameters are called formal parameters. When calling the function, you also need to pass the corresponding parameters. These parameters are called actual parameters.
// 带参数的函数声明
function 函数名(形参1, 形参2 , 形参3...) { // 可以定义任意多的参数,用逗号分隔
 // 函数体
}
// 带参数的函数调用
函数名(实参1, 实参2, 实参3...);
  • Case: Use a function to find the sum of any two numbers
function getSum(num1, num2) {
 console.log(num1 + num2);
}
getSum(1, 3); // 4
getSum(6, 5); // 1

The passing process of function parameters

// 声明函数
function getSum(num1, num2) {
 console.log(num1 + num2);
}
// 调用函数
getSum(1, 3); // 4
getSum(6, 5); // 11
  • 1. The actual parameter value is passed to the formal parameter when called
  • 2. The formal parameter is simply understood as: variable without declaration
  • 3. Multiple parameters of actual and formal parameters are separated by commas (,)

The problem of the number of function parameters and actual parameters does not match

function sum(num1, num2) {
 console.log(num1 + num2);
}
sum(100, 200); // 形参和实参个数相等,输出正确结果
sum(100, 400, 500, 700); // 实参个数多于形参,只取到形参的个数
sum(200); // 实参个数少于形参,多的形参定义为undefined,结果为NaN
  • Note: In JavaScript, the default value of the formal parameter is undefined .

summary

  • Functions can take parameters or no parameters
  • When declaring a function, the parameters in the parentheses of the function name are formal parameters, and the default value of the formal parameters is undefined
  • When calling a function, the actual parameters in the parentheses of the function name
  • Multiple parameters are separated by commas
  • The number of formal parameters can not match the number of actual parameters, but the result is unpredictable, we try to match

The return value of the function

return statement

  • The syntax format of the return statement is as follows:
// 声明函数
function 函数名(){
 ...
 return 需要返回的值;
}
// 调用函数
函数名(); // 此时调用函数就可以得到函数体内return 后面的值
  • When using the return statement, the function will stop execution and return the specified value
  • If the function does not return, the return value is undefined
  • For example, a sum() function is declared, the return value of the function is 666, and the code is as follows:
// 声明函数
function sum(){
 ...
 return 666;
}
// 调用函数
sum(); // 此时 sum 的值就等于666,因为 return 语句会把自身后面的值返回给调用者
  • Case 1: Use a function to find the maximum value of any two numbers
function getMax(num1, num2) {
 return num1 > num2 ? num1 : num2;
}
console.log(getMax(1, 2));
console.log(getMax(11, 2));
  • Case 2: Use functions to find the maximum value in any array
    • Find the largest value in the array [5,2,99,101,67,77].
//定义一个获取数组中最大数的函数
function getMaxFromArr(numArray){
 var maxNum = 0;
 for(var i =0;i < numArray.length;i++){
 if(numArray[i] > maxNum){
 maxNum = numArray[i];
 }
 }
 return maxNum;
}
var arrNum = [5,2,99,101,67,77];
var maxN = getMaxFromArr(arrNum); // 这个实参是个数组
alert('最大值为:'+ maxN);

return termination function

  • The code after the return statement is not executed.
function add(num1,num2){
 //函数体
 return num1 + num2; // 注意:return 后的代码不执行
 alert('我不会被执行,因为前面有 return');
}
var resNum = add(21,6); // 调用函数,传入两个实参,并通过 resNum 接收函数返回值
alert(resNum); // 27

return value

  • return can only return one value . If multiple values ​​are separated by a comma, the last one shall prevail .
function add(num1,num2){
 //函数体
 return num1,num2;
}
var resNum = add(21,6); // 调用函数,传入两个实参,并通过 resNum 接收函数返回值
alert(resNum); // 6
  • Case: Create a function to implement addition, subtraction, multiplication, and division between two numbers, and return the result
var a = parseFloat(prompt('请输入第一个数'));
var b = parseFloat(prompt('请输入第二个数'));
function count(a, b) {
 var arr = [a + b, a - b, a * b, a / b];
 return arr;
}
var result = count(a, b);
console.log(result);

Function without return returns undefined

  • Functions have return values
    • 1. If there is a return, return the value after return
    • 2. If you do not have a return undefined is returned

The difference between break, continue, return

  • break: end the current loop body (such as for, while)
  • continue: Jump out of this loop and continue to execute the next loop (such as for, while)
  • return: Not only can you exit the loop, you can also return the value in the return statement, and you can also end the code in the current function body

See through the function through the juicer

Use of arguments

  • When we are not sure how many parameters are passed, we can use arguments to get them. In JavaScript, arguments are actually a built-in object of the current function . All functions have a built-in arguments object, and all the passed actual parameters are stored in the arguments object .
  • The argument display form is a pseudo-array , so it can be traversed. The pseudo array has the following characteristics:
    • Has a length attribute
    • Store data by index
    • Push, pop and other methods without array
  • Case: Use a function to find the maximum value of any number
function maxValue() {
 var max = arguments[0];
 for (var i = 0; i < arguments.length; i++) {
     if (max < arguments[i]) {
     max = arguments[i];
     }
 }
     return max;
}
console.log(maxValue(2, 4, 5, 9));
console.log(maxValue(12, 4, 9));

Function case

  • Case 1: Use function encapsulation to flip any array
function reverse(arr) {
var newArr = [];
for (var i = arr.length - 1; i >= 0; i--) {
    newArr[newArr.length] = arr[i];
    }
    return newArr;
}
var arr1 = reverse([1, 3, 4, 6, 9]);
console.log(arr1);
  • Case 2: Using function encapsulation to sort the array-bubble sort
function sort(arr) {
    for (var i = 0; i < arr.length - 1; i++) {
        for (var j = 0; j < arr.length - i - 1; j++) {
            if (arr[j] > arr[j + 1]) {
                var temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
        }
       }
    }
        return arr;
}
  • Case 3: Judging Leap Year
function isRun(year) {
 var flag = false;
 if (year % 4 === 0 && year % 100 !== 0 || year % 400 === 0) {
     flag = true;
     }
     return flag;
}
console.log(isRun(2010));
console.log(isRun(2012));

Function can call another function

  • Because each function is an independent code block, used to complete special tasks, so it is often used in the case of functions calling each other.
function fn1() {
     console.log(111);
     fn2();
     console.log('fn1');
}
function fn2() {
     console.log(222);
     console.log('fn2');
}
fn1();

Two ways of function declaration

Custom function method (named function)

  • Use the function keyword function to customize the function mode.
// 声明定义方式
function fn() {...}
// 调用 
fn();
  • Because it has a name, it is also called a named function
  • The code that calls the function can either be placed before or after the declared function

Function expression mode (anonymous function)

// 这是函数表达式写法,匿名函数后面跟分号结束
var fn = function(){...};
// 调用的方式,函数调用必须写到函数体下面
fn();
  • Because the function has no name, it is also called an anonymous function
  • What is stored in this fn is a function 
  • The principle of the function expression method is the same as the method of declaring variables
  • Function call code must be written after the function body

Guess you like

Origin blog.csdn.net/baidu_41388533/article/details/108612661