函数

    技术2023-11-24  96

    1.默认参数 1.1古代使用三目运算来看是否传了实参,没传就使用默认参数 1.2现代使用’=’,直接等于什么默认参数就是什么,下面就是用默认参数做的一个排序例子。

    function sort1 (array, type="从小到大") { return array.sort(function(a,b){ return type==="从小到大" ? a-b : b-a }) } console.log(sort1([1,2,6,1,4,98,1,3,6,0,4], '从大到小'))

    2.箭头函数 2.1与以往的function相比,箭头函数有以下几个特性 1.当只有一个参数时可以省略括号。 2.当只有一句代码块时,可以省略大括号,return都不用写。 2.2 使用箭头函数来完成过滤操作

    let arr = [1,2,3,4,5,6] console.log(arr.filter( value => value>3 )) //[4,5,6]

    2.3 箭头函数中的this就是上一层的this。

    3.递归算法 3.1 原理就是每次让参数和参数减一返回的值相乘,到一就停止 3.2

    function factorial (num) { if(num == 1){ return 1 } return num * factorial(num-1) } console.log(factorial(5)) //120

    3.3其运行过程就是

    return 5 * (num-1) 5*4*3*2*1 return 4 * (num-1) 4*3*2*1 return 3 * (num-1) 3*2*1 return 2 * (num-1) 2*1 return 1

    3.4 简写为

    function factorial (num) { return num === 1 ? 1 : num * factorial(num-1) } console.log(factorial(3)) //6

    4.使用递归完成求和

    function add (...num) { if(num.length === 0){ return 0 } return num.pop() + add(...num) } console.log(add(1,2,3,4,5,6,7,8,9))

    4.1可简写为

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

    5.使用递归完成倒三角

    function star (num) { return num ? document.write("*".repeat(num)+'</br>') || star(--num) : '' } star(5)

    6.回调函数就是在一个函数中被调用的那个函数。

    7.点语法 7.1在赋值运算中 点在右边就是展开

    let arr = [1,2,3,5,6,7] let [a,b,c] = [...arr] console.log(c) //3

    点在左边就是收

    let arr = [1,2,3,5,6,7] let [a,b,...c] = [...arr] console.log(c)//[3,5,6,7]

    7.2在函数中一般都是收,把参数都收集在一起,和arguments一样,但要放在其他参数后面避免把所有的参数都收了

    function add (discount=0, ...price) { let all = price.reduce((a,b) => a+b) return Math.round(all * (1-discount)) } console.log(add(.5,1,2,3,4,5,6,7,8,9)) //23
    Processed: 0.080, SQL: 10