Fourth, the basic concept and use of functions

1. The concept and characteristics of functions

  1. The concept of a function: it consists of a bunch of codes that implement a certain function and can be directly called or event-controlled code segment. In a computer, a function can be regarded as an encapsulated functional code block

    For example, household appliances that can be seen everywhere in life: they are assembled from a pile of circuit boards and components, can realize one or more functions, and can be controlled by remote control or switch

  2. Features of the function

    • Optional execution: Once packaged, it can be optionally used in other programs in the future
    • Repeated execution: After encapsulation, it can be called repeatedly in different programs or functions
    • Ignore details: After encapsulation, every time you use a function, you don't need to consider its internal implementation
  3. composition

    • name
    • function code
    • Entrance
    • exit

2. Function creation and execution

  1. Creation function - packaged container

    • Declarative:
      • Keywords for declaring functions:function
      • function 函数名(){...}
        • function: declaration keyword
        • 函数名: The name of the function, which can be used to find this function
        • (): parameter list, function entry
        • {}: The code that makes up the function, the execution statement of the function
    • Assignment:
      • Use variables for assignment
      • var 变量名 = function(){}
  2. Function Execution - use the functions inside this container

    • Execute directly:名字()
      • like:printTable()
      • Note: In any case, as long as 名字()will be executed as a function, even if it is not a function
    • Event execution:事件源.on事件名 = 函数
      • like:btn.onclick = printTable
      • like:btn.onclick = function(){...}
  3. According to the wording, the classification of functions:

    • Well-known functions:function fn(){...}
      • normal function, normal use
    • Unnamed function:function(){...}
      • Incomplete function, not allowed to use directly, direct use will report an error, can only be used as a value
      1. As the value of an assignment-creating function :var abc = function(){}
      2. Used as an event handler , executed by the event:btn.onclick = function(){}
      3. Used as an actual parameter (callback function: when a function A is passed to another function B as a parameter, the function A as a parameter is the callback function of function B):fn( function(){} )
      4. Used as the return value of the function (closure function: when a function A returns another function B, then function B is called the closure function of function A):function fun(){ return function(){} }
      5. As a function body of an anonymous function use:(function(){})()
    • anonymous function:(function(){})()
      • will execute immediately
      • Use anonymous functions to generate scopes (see next chapter)
  4. event (execute function)

    • An event is a manifestation of behavior, action, and interaction. It needs to be actively triggered by certain behaviors, and after the trigger, the process of executing the corresponding function

    • Mouse class:

      • click: click
      • Double click: dblclick
      • press: mousedown
      • lift up: mouseup
      • move: mousemove
      • Enter: mouseover / mouseenter
      • leave: mouseout / mouseleave
      • Right click: contextmenu
    • Keyboard

      • Press: keydown
      • lift up: keyup
      • Press and lift: keypress
    • page or browser class

      • Scroll: scroll
      • load: load
      • Change size: resize
    • Form class:

      • Get the focus: focus
      • lose focus: blur
      • Change content: change
      • input: input
      • submit: submit
      • reset: reset
    • The way to bind the event: 事件源.on事件名 = 事件处理函数. like:btn.onmousemove = function(){...}

      • Note: which event source the current event should be added to
      • Note: what behavior should the current event trigger

3. Function parameters - entry

  • When defining a function, we may pre-define the execution methods of different functions in the function in advance, or may process different data in the future.
  • When the function is executed, in order to dynamically transmit data or different states to the function, the function can choose to execute different functions according to the incoming data, thus generating parameters
  1. Classification of parameters
    • When the function is executed, the parameters sent are called actual parameters.
    • When a function is defined, the parameters received are called formal parameters.
    • The relationship between the actual parameter and the formal parameter: the actual parameter is passed to the formal parameter, the formal parameter saves the actual parameter, and the actual parameter is assigned to the formal parameter. Similar to variable assignment, the formal parameter needs to follow the variable naming convention.
      function log(text){
              
              
      	console.log(text)
      }
      log("hello");		// hello
      log(365);			// 365
      
  2. Parameter type: The function itself does not limit the parameter type, and any type of data can be passed in (except for functions that have specified parameter types)
  3. Number of parameters: The function itself does not limit the number of parameters, and any number of data can be passed in (except for functions that have specified the number of parameters)
    • When the number of actual parameters and formal parameters is consistent: the parameter list is from left to right, and the actual parameters and formal parameters are in one-to-one correspondence
    • When there are more formal parameters than actual parameters: the extra formal parameters have not received actual parameters, indicating that no value has been assigned, which isundefined
    • When there are more actual parameters than formal parameters: the extra actual parameters are not accepted by the formal parameters, you can use argumentsthe get
  4. arguments
    • The built-in array-like object inside the function is used to receive all the actual parameters of the current function.
    • Since argumentsit is an array-like, it has array index and length
      • arguments.length: The length of the array, the number of actual parameters
      • Parsing argumentseach data: with the index n, the value range of n is: 0~length-1
        • arguments[n]
      function fn(){
              
              
          for(var i=0;i<arguments.length;i++){
              
              
              console.log(arguments[i])
          }
      }
      fn(4,25,16,785,345,"WORLD");
      
  5. Application of parameters
    • When the number of parameters of the function is determined, use the specific number of formal parameters to receive
      // 编写函数,计算两个任意数字的和
      function sum(num1, num2){
              
              
      	console.log(num1 + num2);
      }
      sum(4,6);		// 10
      sum(5,9);		// 14
      sum(12,23);		// 35
      
    • When the number of parameters of the function is uncertain, you can use arguments to get all the actual parameters
      // 编写函数,计算任意个任意数字的和
      function sum(){
              
              
          var s = 0;
          for(var i=0;i<arguments.length;i++){
              
              
              s += arguments[i];
          }
          console.log(s);
      }
      sum(1,2);			// 3
      sum(4,2,6,2,8,1);	// 23
      sum(16,45,21,9);	// 91
      

Fourth, the return value of the function - export

  • When we have a function that processes data, in order to obtain the data results processed by the function outside the function, and use the data for secondary use or for other purposes. We set the return value for the function, that is, add the function's exit
  1. Set return value - keyword:
    • return 要返回的数据或变量
    • return returns the execution result inside the function to the execution statement of the function , and immediately ends the execution of the function
    • If a function does not return, then its return value is undefined
      function fn(){
              
              
      	return "hello";
      }
      console.log( fn() );		// hello
      
      function fun(){
              
              }
      console.log( fun() );		// undefined
      
      
  2. The type of return value: the function itself does not restrict the return value type, and can return any type of data (except for functions that have specified the return value type)
  3. Number of return values: Because return has the function of ending the function, a function can only have one return value (if you need to return multiple data, you can use an array or object to package the data before returning)
    function fn(){
          
          
    	console.log(1);
    	return "hello";
    	console.log(2);
    }
    fn();		// 1
    
  4. Application scenarios of return value
    • Functions that implement functions: may not need to return a value
      function log(text){
              
              
      	console.log(text);
      }
      // 简化了打印功能,不需要返回值
      log("hello");		// hello
      
    • Functions that process data: try to add return values
      function sum(a,b,c){
              
              
      	return a+b+c;
      }
      // 计算指定数据累加和,将计算结果返回到函数外部
      console.log( sum(5,2,4) );	// 11
      

5. Practice

  1. Write a function that calculates the sum/difference/product/quotient/surplus of two numbers. Requirement: use the method of passing parameters
  2. Write a function to calculate the size of three different numbers and print them in ascending order. use exhaustive method
  3. Write functions that sum or product any number of arbitrary numbers
  4. Write a function to calculate the two-digit odd number that can be formed between any two numbers. The number must be a single digit.
    For example: Calculate the odd number that can be formed between 0 and 3: 01, 21, 03, 13, 23, 31
  5. A company uses a public telephone to transmit data. The data is a four-digit integer, which is encrypted during the transmission process. The encryption rules are as follows: add 5 to each number, and then replace the number with the remainder when divided by 10, and then replace the number One bit is exchanged with the fourth bit, and the second bit is exchanged with the third bit. Please write a function, pass in the original text, and output the cipher text

Guess you like

Origin blog.csdn.net/weixin_41636483/article/details/115248347