【问题标题】:Can I store function in key-value pair where the function is the key for JavaScript?我可以将函数存储在键值对中,其中函数是 JavaScript 的键吗?
【发布时间】:2020-12-03 21:53:42
【问题描述】:

我有如下功能列表

function max(result, current) {
    if (result > current) return result
    else return current
}

function min(result, current) {
    if (result < current) return result
    else return current
}

function sum(result, current) {
    return result + current
}

function product(result, current) {
    return result * current
}

我可以将它们存储在一个数组中,如下所示

const mapOfFunctions = [
    sum,
    product,
    max,
    min,
]

但是我可以将它们存储为键值对,其中函数是键吗?

const mapOfFunctions = [
    {sum: 0},
    {product: 1},
    {max: Number.MIN_SAFE_INTEGER},
    {min: Number.MAX_SAFE_INTEGER},
]

【问题讨论】:

  • 这听起来非常像XY Problem。这里的目标是什么?您不能将函数本身用作对象键,因为对象键是隐式字符串

标签: javascript arrays dictionary functional-programming


【解决方案1】:

是的。 Map 类允许您使用任何对象作为键:

const identities = new Map([
  [sum, 0],
  [product, 1],
  [max, Number.MIN_SAFE_INTEGER],
  [min, Number.MAX_SAFE_INTEGER]
]);

const sumIdentity = identities.get(sum); // 0
const productIdentity = identities.get(product); // 1

【讨论】:

猜你喜欢
  • 2011-04-05
  • 1970-01-01
  • 1970-01-01
  • 2013-01-19
  • 1970-01-01
  • 2020-08-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多