簡體   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