recursive

  • What is recursion?

In a program, recursion is a function calling itself directly or indirectly.

  • Elements of recursion?

    1 Call yourself

    2 have an end condition

  • Transforming ideas

The process of reducing a problem from difficult to easy, from complex to simple, from complex to simple is called reduction, which is short for transformation and conclusion.

Here are some more examples to get a feel for the idea of recursion. Let’s get started!

Chestnut 1: Find the sum of 1~100

// get 99 from 99 // get 98 from 99 // get 100 from 99 // get 98 from 99 Sum (1) {function sum(n){if(n == 1){return 1; } return sum(n - 1) + n; } var num = sum(100); console.log(num); / / 5050Copy the code

Chestnut 2: Find the factorial

/ / 1! 1 / / 2! 1! * 2 / / 3! 2! * 3 / /... // n! (n-1)! * n function factorial(n){ if( n == 1){ return 1; } return factorial(n - 1) * n; } / / 5! = 1 * 2 * 3 * 4 * 5 console.log(factorial(5)); / / 120Copy the code

Chestnut 3: Exponentiation

// 1^m 1 * 1^(m-1) = 1^m = 1 // 2^m 2 * 2^(m-1) = 2^m //... // Every number to the first power is equal to itself, e.g. 2^1 = 2; Function power(n, m){if(m == 1){return n; } return power(n, m-1) * n; } the console. The log (power (4, 3)); 48 / / / / 4 * 4 * 4 = 48Copy the code

Chestnut 4: Fibonacci series

// Fibonacci numbers: 1 1 2 3 5 8 13 21 34... // Start with the third term, the value of the latter term is the sum of the previous two terms // first term 1 // second term 1 // third term 1 + 1 = 2 // fourth term 1 + 2 = 3 //... Function Fibonacci (n){if(n <= 2){return 1; // function Fibonacci (n){return 1; } return fibonacci(n - 2) + fibonacci(n - 1); } console.log(fibonacci(10)); / / 55Copy the code

Chestnut 5: Add borders to all elements on the page

Function getChildNodes(node){var nodeList = node.childnodes; var nodeList = node.childnodes;  For (var I = 0; var I = 0; i < nodeList.length; NodeType == 1 Element node /2 attribute node /3 text node var // nodeType == 1 element node /2 attribute node /3 text node childNode = nodeList[i]; Childnode.nodetype == 1){childNode.style.border = '1px solid red'; getChildNodes(childNode); } } } getChildNode(document.body);Copy the code

Code optimization and upgrade:

function getChildNode(node){ var nodeList = node.childNodes; var res = []; for(var i = 0; i < nodeList.length; i++){ var childNode = nodeList[i]; if(childNode.nodeType ==1){ res.push(childNode); var temp = getChildNode(childNode0; res = res.concat(temp); } } return res; } // 1. The first call gets all the child elements of the body and puts all the child elements in the res. // all children of the child element have a return value // 3. Var arr = getChildNode(document.body); var arr = getChildNode(document.body); for(var i = 0; i < arr.length; i++){ var child = arr[i]; child.style.border = '1px solid red'; }Copy the code

The effect is shown below:

closure

concept

  • What is a closure?

The function within the function, the inside function can access the variables of the outside function, and the outside variables are part of the inside function.

function outer(){ var num = 0; Return function add(){// call num++ from outer; Console. log(num); console.log(num); } } var func = outer(); func(); // 1 func(); / / 2Copy the code
  • How does closure work?

Scope access principle: A parent scope cannot directly access variables in a child scope

  • What problems do closures solve?

1) The data inside the closure is not accessible to outsiders

2) The problem to be solved is indirect access to the data

function foo(){ var num = 123; return num; } var x = foo(); // Use the return keyword to return the data inside the function. This data can only be used once console.log(x); Var y = foo(); var y = foo(); console.log(y); // 123 console.log(x === y); // true // They must be equal because they are numeric types, but what about reference types?Copy the code

Function foo(){var obj = {name: 'foo '; } return obj; } var o1 = foo(); var o2 = foo(); console.log(o1 == o2); // false // The function returns a new object each timeCopy the code
  • The basic pattern for closures
function outer(){ var num = 123; Return function inner(a){// if(a! == undefined){ num = a; }else{// If no parameter is sent, the value is directly returned. } } } var func = outer(); func(456); / / 456Copy the code

1) Create a function (inner) inside the outer function (outer). In this inner function, you can manipulate the data in the outer function (outer)

Select * from outer; select * from inner;

Select * from outer; select * from outer;

4) Using this inner function, you can modify the variables inside the inner function externally

Get multiple data using closures

Function bar(){var name = 'c '; var age = 18; Return {getName: function(){return name; }, getAge: function(){ return age; SetName: function(value){name = value; return name; }, setAge: function(value){age = value; return age; }}} var obj = bar(); console.log(obj.getName()); / / zhang SAN console. The log (obj. GetAge ()); // 18 console.log(obj.setname (' Li ')); / / li si console. The log (obj. SetAge (' 20 ')); / / 20Copy the code

The role of closures

Function bar(){var name = 'c '; var age = 18; return { getName: function(){ return name; }, setName: function(value){ name = value; return name; }}} var obj = bar(); Obj. Name (' bill ');Copy the code

Function:

The basic function: you can use closures to return functions or methods that modify the data inside the function.

Create a private space to protect data; External access to data can only be enhanced by functions. In the provided methods, some validation logic can be set to make the data more secure.

An exercise in closures

Threads: A thread can only handle one thing at a time, and multiple threads can perform multiple things at the same time

Javascript is single threaded!!

Javascript has three tasks:

1) Rendering tasks

2) Js code to perform tasks

3) Event processing tasks

Executing tasks for Javascript code:

1) Finish the main task (code task) first

2) Perform secondary tasks (including code in callback functions in setTimeout and setInterval)

SetTimeout function: execute the specified callback function after the specified time at least, because the code in the main task is finished, then check the setTimeout function, whether the execution time is up.

Such as the problem code:

for(var i = 0 ; i < 10; i++){ setTimeout(function(){ console.log(j); },0); }Copy the code

Problem solving code:

for(var i = 0; i < 10; i++){ function bar(j){ return function(){ console.log(i); // 0 1 2 3 4 5 6 7 8 9}; } var f = bar(i); setTimeout(f, 0); }Copy the code

Chestnut: Get div, click print the corresponding div number

var divs =document.getElemetsByTagNmae('div'); for(var i = 0; i < divs.length; i++){ var div = divs[i]; Div. Onclick = function(j){return function(){console.log(' I am the first '+ (j + 1) +' div'); } }(i); } // Immediately execute the function expression (funciton(){console.log(' XXX '); } ());Copy the code