繁体   English   中英

我可以将 function 存储在键值对中,其中 function 是 JavaScript 的键吗?

[英]Can I store function in key-value pair where the function is the key for JavaScript?

我有一个功能列表如下

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,
]

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

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

是的。 Map class 允许您使用任何 object 作为密钥:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM