草庐IT

【JavaScript】31_高阶函数(回调函数)

魔天伦哦 2023-03-28 原文
目前我们的函数只能过滤出数组中age属性小于18的对象,

我们希望过滤更加灵活:

比如:过滤数组中age大于18的对象

age大于60的对象

age大于n的对象

过滤数组中name为xxx的对象

过滤数组中的偶数

...

一个函数的参数也可以是函数,

如果将函数作为参数传递,那么我们就称这个函数为回调函数(callback)

<script>
class Person {
constructor(name,age){
this.name = name;
this.age = age
}
}

const personArr = [
new Person('孙悟空',180),
new Person('沙和尚',36),
new Person('红孩儿',5),
new Person('白骨精',19),
]

//filter()函数式用来对数组进行过滤的
function filter(arr, cb) {
const newArr = []

// console.log("-->", cb)
// cb()

for (let i = 0; i < arr.length; i++) {
// arr[i].age >= 18
// arr[i].age > 60
// arr[i].age > n
// arr[i].name === "xxx"
// arr[i] % 2 === 0
if (cb(arr[i])) {
newArr.push(arr[i])
}
}

return newArr
}

function fn(a){
return a.name === "孙悟空"
}

result = filter(personArr, fn)
console.log(result)
</script>

14、高阶函数

高阶函数(回调函数)

  • 如果一个函数的参数或返回值是函数,则这个函数就称为高阶函数
  • 为什么要将函数作为参数传递?(回调函数有什么作用?)
  • 将函数作为参数,意味着可以对另一个函数动态的传递代码
<script>
class Person {
constructor(name,age){
this.name = name
this.age = age
}
}

const personArr = [
new Person('孙悟空',18),
new Person('沙和尚',37),
new Person('红孩儿',3),
new Person('白骨精',54),
]

function filter(arr,cb){
const newArr = []

for(let i = 0; i <arr.length; i++){
if(cb(arr[i])){
newArr.push(arr[i])
}
}
return newArr
}

// 我们这种定义回调函数的形式比较少见,通常回调函数都是匿名函数
function fn(a){
return a.name === '孙悟空'
}

result = filter(personArr,a => a.name === '孙悟空')
result = filter(personArr,a => a.age >= 18)

const arr = [1,2,3,,4,5,6,7,8,9,10]
result = filter(arr,a => a % 2 === 0)

console.log(result)
</script>

动态生成新数组,非破坏性函数

希望在someFn()函数执行时,可以记录一条日志

在不修改原函数的基础上,为其增加记录日志的功能

可以通过高阶函数,来动态的生成一个新函数

<script>
function someFn(){
return 'hello'
}

function outer(cb){
return () => {
console.log('记录日志~~~')
const result = cb()
return result
}
}

let result = outer(someFn)

function test(){
console.log("test~~~")
return 'test'
}
let newTest = outer(test)
newTest()
</script>

有关【JavaScript】31_高阶函数(回调函数)的更多相关文章

  1. ruby - 在没有 sass 引擎的情况下使用 sass 颜色函数 - 2

    我想在一个没有Sass引擎的类中使用Sass颜色函数。我已经在项目中使用了sassgem,所以我认为搭载会像以下一样简单:classRectangleincludeSass::Script::FunctionsdefcolorSass::Script::Color.new([0x82,0x39,0x06])enddefrender#hamlengineexecutedwithcontextofself#sothatwithintemlateicouldcall#%stop{offset:'0%',stop:{color:lighten(color)}}endend更新:参见上面的#re

  2. ruby - 如何在 Rails 4 中使用表单对象之前的验证回调? - 2

    我有一个服务模型/表及其注册表。在表单中,我几乎拥有服务的所有字段,但我想在验证服务对象之前自动设置其中一些值。示例:--服务Controller#创建Action:defcreate@service=Service.new@service_form=ServiceFormObject.new(@service)@service_form.validate(params[:service_form_object])and@service_form.saverespond_with(@service_form,location:admin_services_path)end在验证@ser

  3. ruby-on-rails - 在 ruby​​ 中使用 gsub 函数替换单词 - 2

    我正在尝试用ruby​​中的gsub函数替换字符串中的某些单词,但有时效果很好,在某些情况下会出现此错误?这种格式有什么问题吗NoMethodError(undefinedmethod`gsub!'fornil:NilClass):模型.rbclassTest"replacethisID1",WAY=>"replacethisID2andID3",DELTA=>"replacethisID4"}end另一个模型.rbclassCheck 最佳答案 啊,我找到了!gsub!是一个非常奇怪的方法。首先,它替换了字符串,所以它实际上修改了

  4. ruby - 在 Ruby 中有条件地定义函数 - 2

    我有一些代码在几个不同的位置之一运行:作为具有调试输出的命令行工具,作为不接受任何输出的更大程序的一部分,以及在Rails环境中。有时我需要根据代码的位置对代码进行细微的更改,我意识到以下样式似乎可行:print"Testingnestedfunctionsdefined\n"CLI=trueifCLIdeftest_printprint"CommandLineVersion\n"endelsedeftest_printprint"ReleaseVersion\n"endendtest_print()这导致:TestingnestedfunctionsdefinedCommandLin

  5. ruby - 有人可以帮助解释类创建的 post_initialize 回调吗 (Sandi Metz) - 2

    我正在阅读SandiMetz的POODR,并且遇到了一个我不太了解的编码原则。这是代码:classBicycleattr_reader:size,:chain,:tire_sizedefinitialize(args={})@size=args[:size]||1@chain=args[:chain]||2@tire_size=args[:tire_size]||3post_initialize(args)endendclassMountainBike此代码将为其各自的属性输出1,2,3,4,5。我不明白的是查找方法。当一辆山地自行车被实例化时,因为它没有自己的initialize方法

  6. ruby - 在 Ruby 中按名称传递函数 - 2

    如何在Ruby中按名称传递函数?(我使用Ruby才几个小时,所以我还在想办法。)nums=[1,2,3,4]#Thisworks,butismoreverbosethanI'dlikenums.eachdo|i|putsiend#InJS,Icouldjustdosomethinglike:#nums.forEach(console.log)#InF#,itwouldbesomethinglike:#List.iternums(printf"%A")#InRuby,IwishIcoulddosomethinglike:nums.eachputs在Ruby中能不能做到类似的简洁?我可以只

  7. C51单片机——实现用独立按键控制LED亮灭(调用函数篇) - 2

    说在前面这部分我本来是合为一篇来写的,因为目的是一样的,都是通过独立按键来控制LED闪灭本质上是起到开关的作用,即调用函数和中断函数。但是写一篇太累了,我还是决定分为两篇写,这篇是调用函数篇。在本篇中你主要看到这些东西!!!1.调用函数的方法(主要讲语法和格式)2.独立按键如何控制LED亮灭3.程序中的一些细节(软件消抖等)1.调用函数的方法思路还是比较清晰地,就是通过按下按键来控制LED闪灭,即每按下一次,LED取反一次。重要的是,把按键与LED联系在一起。我打算用K1来作为开关,看了一下开发板原理图,K1连接的是单片机的P31口,当按下K1时,P31是与GND相连的,也就是说,当我按下去时

  8. Python 刷Leetcode题库,顺带学英语单词(31) - 2

    ValidPalindromeGivenastring,determineifitisapalindrome,consideringonlyalphanumericcharactersandignoringcases. [#125]Example:"Aman,aplan,acanal:Panama"isapalindrome."raceacar"isnotapalindrome.Haveyouconsiderthatthestringmightbeempty?Thisisagoodquestiontoaskduringaninterview.Forthepurposeofthisproblem

  9. ruby-on-rails - 将字符串转换为 ruby​​-on-rails 中的函数 - 2

    我需要一个通过输入字符串进行计算的方法,像这样function="(a/b)*100"a=25b=50function.something>>50有什么方法吗? 最佳答案 您可以使用instance_eval:function="(a/b)*100"a=25.0b=50instance_evalfunction#=>50.0请注意,使用eval本质上是不安全的,尤其是当您使用外部输入时,因为它可能包含注入(inject)的恶意代码。另请注意,a设置为25.0而不是25,因为如果它是整数a/b将导致0(整数)。

  10. ruby-on-rails - 使用 javascript 更改数据方法不会更改 ajax 调用用户的什么方法? - 2

    我遇到了一个非常奇怪的问题,我很难解决。在我看来,我有一个与data-remote="true"和data-method="delete"的链接。当我单击该链接时,我可以看到对我的Rails服务器的DELETE请求。返回的JS代码会更改此链接的属性,其中包括href和data-method。再次单击此链接后,我的服务器收到了对新href的请求,但使用的是旧的data-method,即使我已将其从DELETE到POST(它仍然发送一个DELETE请求)。但是,如果我刷新页面,HTML与"new"HTML相同(随返回的JS发生变化),但它实际上发送了正确的请求类型。这就是这个问题令我困惑的

随机推荐