【问题标题】:How to know a JavaScript function accepts a simple parameter or a destructured object?如何知道一个 JavaScript 函数接受一个简单的参数或一个解构的对象?
【发布时间】:2022-12-07 12:32:38
【问题描述】:

考虑这两个函数:

const render = (entity) => {
   // function body
}

const render = ({
    entity,
    isAdmin
}) => {
   // function body
}

现在假设我想调用这个函数。如果它接受一个解构的对象,我应该以不同的方式传递参数。

render({
    name: 'John', 
    age: 40
})

// or

render({
    entity: {
      name: 'John',
      age: 40
    },
    isAdmin: true
})

有没有办法让我知道函数是否接受解构对象作为其参数?

请注意,render.length 为这两个函数返回 1。 arguments 对我没有帮助,因为它可以访问里面功能,而不是它之外。

【问题讨论】:

  • 是的,使用 Typescript 或禁止使用 Typescript,请阅读文档。否则,不

标签: javascript


【解决方案1】:

我不清楚为什么你需要这样做。函数的参数不会也不能改变,在调用函数之前你应该总是知道函数接受什么参数。

但是,仅出于此目的,这里有一个您可以执行此操作的方法示例。将函数字符串化,然后使用正则表达式匹配参数列表中的({ })

const render1 = (entity) => {}

const render2 = ({
    entity,
    isAdmin
}) => {}

function doesDestructure(func){
  return !!func.toString().replaceAll("
", "").match(/({.+})/gm)
}

console.log(doesDestructure(render1))
console.log(doesDestructure(render2))

【讨论】:

    猜你喜欢
    • 2023-03-22
    • 2021-03-07
    • 1970-01-01
    • 2012-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多