2分钟搞定JS面试 / 高阶函数

2025-06-07

2分钟搞定JS面试 / 高阶函数

问题:
解释 Javascript 中的高阶函数。

快速回答:
这些是返回其他函数的函数。

更新:正如@mazentouati在评论中指出的那样,高阶函数也是接受函数作为参数的函数。维基百科

图像

更长的答案:
在 JavaScript 中,你可以返回任何类型的对象作为函数的结果,或者接收任何类型的对象作为参数。这意味着你可以创建一个返回函数的函数。



function higherFunction() {
  return function regularFunction() {
    console.log('Hello world!')
  }
}

const a = higherFunction() // won't print anything
a() // Hello world!


Enter fullscreen mode Exit fullscreen mode

您还可以尝试创建更多嵌套函数。



const a = () => () => () => () => console.log('Hello world')
const b = a()
const c = b()
const d = c()

d() // Hello world!


Enter fullscreen mode Exit fullscreen mode

您可以将函数传递给将按照特定顺序执行函数的函数。



const pipe = (...args) => 
  (init) => 
    args.reduce((acc, cur) => cur(acc), init)

const a = pipe(
 (val) => val + 1,
 (val) => val * 2,
 (val) => console.log("Got", val),
)

a(10) // Got 22


Enter fullscreen mode Exit fullscreen mode

还有更多其他有趣的函数使用方法🤪

现实生活中的例子:
一些框架(angular)和库(MobX)严重依赖装饰器,但装饰器只不过是高阶函数本身。



const logDecorator = (wrapped) => {
  return (...args) => {
    console.log(`Invoked ${wrapped.name} with args ${args}`)
    wrapped(...args)
  }
}

const tmp = (param) => {
  console.log('Do nothing, but just show param:', param) 
}

const wrappedTmp = logDecorator(tmp)
wrappedTmp('Hello world!')
// Invoked tmp with args Hello world!
// Do nothing, but just show param: Hello world!


Enter fullscreen mode Exit fullscreen mode

一些其他库(RxJs)可能使用它作为可配置的助手。



// These functions can by provided by a library itself
const uppercase = (a) => a.toUpperCase();
const removePunctuation = (a) => a.replace(/[^0-9a-zA-Z ]/g, '')

// pipe is a Higher Order Function that returns a function, which will apply all functions one by one
const process = pipe(
  uppercase,
  removePunctuation,
)

console.log(process('qwe-qwe'), process('Hello world!'))
// QWEQWE HELLO WORLD


Enter fullscreen mode Exit fullscreen mode

旧帖:

顺便说一句,我会在这里和推特上发布更多有趣的东西。我们做个朋友吧👋

文章来源:https://dev.to/hexnickk/js-interview-in-2-minutes-higher-order-functions-38kb
PREV
来自前招聘人员的谈判建议
NEXT
2 分钟内完成 JS 面试 / Currying 🥘