1、在JavaScript的世界中,函数也可以是一个对象,一个个值,可以被赋予一个变量,或是更严格的说,可以用一个变量来指向这个函数对象

2、JavaScript定义函数有两种方法:

//方法1(函数叙述法)function sum(para1,para2){  return para1+para2}//方法2(函数运算法)let sum = function(para1,para2){  return para1+para2}//调用函数let s = sum(100,200)

3、使用函数叙述法定义函数时可以在定义之前被调用,而函数运算式法只能在函数定义后调用

4、示例如下

let bookPrice = 300console.log(`book price is ${bookPrice}`)let penPrice = "300"console.log(`pen price is ${penPrice}`)function sumPrice(first,second,third){    return first+second+third}let totalPrice = sumPrice(bookPrice,penPrice)console.log(`Total price is ${totalPrice}`)//运行结果PS F:\jstest> node test1.jsbook price is 300pen price is 300Total price is 300300undefinedPS F:\jstest>

5、当函数要传多个参数时我们可以将函数进行改造

let bookPrice = 300console.log(`book price is ${bookPrice}`)let penPrice = "300"console.log(`pen price is ${penPrice}`)function sumPrice(...Number){    return Number.reduce(function(total,num){        return total+(Number.isNaN(Number(val))?0:Number(val))    })}let totalPrice = sumPrice(bookPrice,penPrice)console.log(`Total price is ${totalPrice}`)

6、reduce() 方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。

reduce() 可以作为一个高阶函数,用于函数的 compose。

注意: reduce() 对于空数组是不会执行回调函数的。

7、箭头函数,

function sumPrice(...Number){  return numbers.reduce(    (total,val)=>total + (Number.isNaN(Number(val))?0:Number(val))  )}

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论

微信小程序

微信扫一扫体验

立即
投稿

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部