js function - up

typora-copy-images-to: media

Function - up

introduce:

Let's ask you a question first. Have you washed your clothes?

How to wash it manually? That basin, take water, put clothes, pour washing powder, wash, rinse and wring dry

It's hard. Is there a simple way?

Use the washing machine, put the clothes in, pour the washing powder, press the switch, and everything is done

There are many such examples in life, ranging from washing machines and air conditioners to faucets and scissors. Each tool has its own different functions. For the convenience and simplicity of life, they will use these tools.

Programmers are a group of people who enjoy life, so there are many such tools in the code, which are the functions we want to learn today.

Summary: tools in code - functions

Concept:

A function is a tool with a certain function. Is a piece of code to complete a function.

Have you ever used functions before?

parseInt() alert() are all functions provided by the system and can be used directly.

The system provides many functions, but not all functions are included, so some functions need to be written by ourselves - custom functions. After the function is defined, it can be used like a system function without writing it again.

So often write code, write a function, and adjust it when necessary.

How to write a custom function?

Define syntax:

function Function name(){
	Code snippet
}
# Function is a keyword. The function name is user-defined. The definition rules are the same as those of variables

When we define the function and refresh it in the page, we will find that this code has not been executed. After the function is defined, it will not be executed automatically, so we need to call it.

Function call:

Syntax:
	Function name()

The calling syntax is very simple, so that when we need to execute the code in the function in the future, we don't have to rewrite so much code. We just need to simply call the originally defined function.

// Definition function: sum two numbers
function fn(){
    var a = 1;
    var b = 2;
    var c = a + b;
    console.log(c);
}
// After the function is defined, it will not be executed automatically and needs to be called manually
fn();

Advantages of function:

  1. The reusability of the code is realized
  2. Modular programming is realized

When we use tools, many tools need us to bring things in. For example, we need to put clothes in when washing clothes. For the tool function, we need to bring parameters.

Functions with arguments:

The values that will change in the function code are replaced by variables, and the entry is the parentheses when declaring the function

function zizeng(a){  // Called formal parameters - formal parameters
    var b = a + 1;
    console.log(b);
}

When calling a function, you need to assign a value to the parameter

zizeng(1); // Arguments - actual parameters, which are actually assigning values to formal parameters

Gets the arguments of the function

There is also a keyword arguments in the function, which can get all the arguments

function css(){
	// Print arguments
	console.log(arguments);
	// Print the number of arguments
	console.log(arguments.length);
}
css("width","100px");

effect:

Get the number of arguments
[the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (IMG ewtlgopw-1628677857213) (media / 156437577280. PNG)]

If there are formal parameters, the same is true. Each value is obtained through subscript

Anonymous function (function with assignment)

Concept: as the name suggests, an anonymous function is a function without a name.

definition:

Syntax:
	function(){
        Code snippet
	}

Of course, anonymous functions can also pass parameters.

Calling: anonymous functions are called at the time of definition

Syntax:
	(function(Formal parameter){
        Code snippet
	})(Argument)

It's very simple. Adding parentheses after curly braces is a call.

(function(a,b){
    var c = a + b;
    document.write(c);
})(1,2);

You can also assign an anonymous function to a variable and call it with the variable name.

Syntax:
# definition
	var fun = function(){
        Code snippet
	}
# call
	fun()

Example:

var fun = function(a,b){
    var c = a + b;
    document.write(c);
}
fun(1,2);

Calling anonymous functions through events

<style>
#myid{
	width:200px;
	height:200px;

	background:#f00;
}
</style>
<body>
	<div id="myid"></div>
</body>
<script>
var oDiv = document.getElementById("myid");
oDiv.onclick=function(){
	alert(123);
}
</script>

Declaration and promotion of variables

There is a program in the browser specially used to parse js code, which is called js parser. The js parser executes js code in two steps:

  1. Pre parsing js code

    The pre parsing process is to find the two keywords var and function in the code. After finding them, store the variables and functions in a place called warehouse, and assign them an initial value. The initial value of the variable is undefined and the initial value of the function is the code segment.

  2. Start interpreting the code line by line in order

    When interpreting the code, the values of variables and functions in the warehouse will change with the interpretation of the code, that is, the assignment of variables and the call of functions.

Pre parsing is divided into pre parsing of variables and pre parsing of functions, that is, the code is parsed before execution, and the names of variables and functions are placed at the front of the current scope.

console.log(a); // Because variable a has not been named, an error will be reported

test(); // The function is undefined, so an error is reported

However, if the variable is named after printing, the situation is different.

// Variable pre parsing
console.log(a); // Because variable a is pre parsed before execution, that is, it has been put into memory, but it has no value, so it is undefined
var a = 1;
/* Pre parsing is equivalent to the following process */
var a; // Put the variable's name first in the current scope
console.log(a);
a = 1;

// Function pre parsing
test(); // Result: 123 the code is pre parsed before execution, and the content of the function is put into memory, so the function defined below can also be called for execution
function test(){
	console.log(123);
}
/* The pre parsing process is as follows: */
function test(){ // Put the function name at the front of the current scope
	console.log(123);
}
test();


Case:

// 1. Assign anonymous function to variable
fn();
var fn = function(){
    console.log(123);
}
// 2. Pre parsing of variables inside the function
function test(){
    console.log(a);
    var a = 10;
}
test();

Summary:

  1. For the variable named with var keyword, the variable name will be promoted to the front of the current scope, and the assignment will not be promoted
  2. The customized function is promoted to the front of the current scope as a whole
  3. If the function has the same name, the latter will overwrite the former
  4. If the variable and function have the same name, the function will be promoted first

Interview questions:

//1. 
var num = 10;
fn1();
function fn1() {
  console.log(num);
  var num = 20;
}

//2. 
var a = 18;
fn2();
function fn2() {
    var b = 9;
    console.log(a);
    console.log(b);
}

//3.
fn3();
console.log(c);
console.log(b);
console.log(a);
function fn3() {
  var a = b = c = 9;
  console.log(a);
  console.log(b);
  console.log(c);
}

//4. Thinking questions
var a = 4;
console.log(a);
a = 6;
console.log(a);
function a() {
    console.log('Ha');
}
a();
a = 10;
console.log(a);

Formal and argument

The parameter brought in when declaring a function is called a formal parameter

When calling a function, the actual value assigned to the formal parameter is the actual parameter

Not all program results need to be output in the page. Sometimes, we just want this piece of code to get a result, and subsequent codes will carry out subsequent processing after getting the result. Then the above function is obviously not applicable. We need to use the return of the function.

Function with return value

Syntax:
	function Function name(){
        return Returned results
	}

The keyword to return the result is return, which can return the result of the function operation to the caller

// Defines a function that increments a specified number
function increase(x){ // Functions with parameters
	var y = x + 1;
	return y
}
// Increment 2 to get the result assigned to variable 3
var a = increase(2);
document.write(a%2); // 1
// Let 5 increment to get the result assigned to variable b
var b = increase(5);
alert(b/2); // 3
// Increment 10 to get the result assigned to variable c
var c = increase(10); 
console.log(c+a-b); // 8

A function with a return value gets a result when calling the function. This result can participate in the operation or be assigned.

For a function with a return value, when the function executes the return keyword, the function terminates, and the code behind return will not run.

// Defines a function that increments a specified number
function increase(x){ // Functions with parameters
	var y = x + 1;
	return y
    // The following code will not be executed
	y += 2;
	alert(y);
}
// Increment 2 to get the result assigned to variable 3
var a = increase(2);
document.write(a);

return's function:

  1. The termination code continues to run
  2. Returns a content in a function

Nesting of functions

The nesting of functions is to call functions in functions.

// Find the average of all elements in the array
/*
analysis:
	1.Sum first
	2.Re average
 */
// Summation function
function sum1(arr) {
	var s = 0;
	for(var i in arr){
		s += arr[i];
	}
	return s;
}
// Average function
function avg1(arr) {
	var sum = sum1(arr);
	var length = arr.length;
	var a = sum/length;
	return a;
}
// call
var arr = [1,6,9,7,2];
var avg = avg1(arr);
console.log(avg);

Function debugging

Sketch Map
[the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-9GjGCMk0-1628677857215)(media/1564373611049.png)]

Keywords: Javascript Front-end

Added by nemonoman on Sat, 25 Dec 2021 20:07:58 +0200