立即执行函数,回调函数,递归

# 1.立即执行

  • 立即执行函数是指函数定义的时候立即执行。
  • 可以用来定义私有作用域防止污染全局作用域。
  • 立即函数执行之后立即释放。
(function () {
    var a = 1;
    console.log(a);
})()  // 1

console.log(a) // a is not defined

# 2.回调函数

  • 一个函数在某一个时刻,被其他函数调用的函数称为回调函数。
  • 比如鼠标的事件等。
  • 回调函数场景很多,对于Ajax异步处理很常见。
    oDiv.addEventListener('click', function() {
        console.log('这就是回调函数');
    })  

# 3.递归调用

  • 递归就是函数内部调用自身的方法。
  • 主要用于数量不确定的循环操作。
  • 要有退出时机否则会陷入死循环。

阶乘:

    function jiecheng(n) {
        return n==1 ? n : n*jiecheng(--n); 
    }
    console.log(jiecheng(5)); // 120

累加:

function sum(...num) {
    return num.length==0 ? 0 : num.pop()+sum(...num);
}
console.log(sum(1,2,3,4,5,6))

倒三角:

function star(row = 5) {
    if (row == 0) return "";
    console.log("*".repeat(row)+'\n');
    star(--row);
  }
  star();

正三角:

function star(n) {
    if(n>5) return "";
    console.log("*".repeat(n) +'\n');
    star(++n);
}
star(0);

# 4.补充

展开语法...

  • 展示语法或称点语法体现的就是收/放特性,做为值时是放,做为接收变量时是收。
let arr = [1,2,3];
let [a , b , c] = [...arr];
console.log(a); // 1
console.log(b); // 2
console.log(c); // 3

[...arr] = [1, 2, 3];
console.log(arr); //[1, 2, 3]
  • 使用展开语法可以替代 arguments 来接收任意数量的参数
function test(...args) {
    console.log(args);
}
test(1,2,3,4,'测试')
  • 也可以用于接收任意参数
function test(name,...args) {
    console.log(name, args);
}
test("后盾人",1,2,3);
Last Updated: 12/7/2020, 3:08:32 PM