[英]Can I store function in key-value pair where the function is the key for JavaScript?
I have a list of functions as below我有一个功能列表如下
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
}
I can store them in an array as below我可以将它们存储在一个数组中,如下所示
const mapOfFunctions = [
sum,
product,
max,
min,
]
But can I store them as a key-value pair, where the function is the key?但是我可以将它们存储为键值对,其中 function 是键吗?
const mapOfFunctions = [
{sum: 0},
{product: 1},
{max: Number.MIN_SAFE_INTEGER},
{min: Number.MAX_SAFE_INTEGER},
]
Yes.是的。 The Map
class lets you use any object as a key: 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.