You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

请求实现从对象反向查找自身的辅助函数/API:优化键调用效率

实现对象键的高效反向查找辅助函数

原生JavaScript并没有内置你设想的valueIn这类反向查找API,但可以通过几种简单的方式实现需求,解决键生成函数重复调用或类型报错的问题:

方案一:通用工具函数(推荐)

写一个工具函数,只调用一次键生成函数,避免重复计算:

function getFromStore(getKeyFn, store) {
  const key = getKeyFn();
  return key !== undefined ? store[key] : undefined;
}

// 使用示例
const store = {key: 1};
// 模拟计算成本较高的键生成函数
const getKey = () => "key" as (string | undefined);
const result = getFromStore(getKey, store); // 结果为1

这种方式安全且通用,不会污染原生对象原型,适合绝大多数场景,尤其是团队协作项目。

方案二:链式调用风格(谨慎使用)

如果偏好你设想的链式语法,可以给String原型扩展方法,但要注意原生原型污染的风险(可能和其他库冲突):

// 扩展String原型
String.prototype.valueIn = function(store) {
  return store[this.toString()];
};

// 使用示例
const store = {key: 1};
const getKey = () => "key" as (string | undefined);
const result = getKey()?.valueIn(store); // 结果为1

方案三:变量缓存(极简写法)

如果不想额外写函数,直接用变量缓存键的结果即可,同样只调用一次键生成函数:

const store = {key: 1};
const getKey = () => "key" as (string | undefined);
const key = getKey();
const result = key ? store[key] : undefined;

内容的提问来源于stack exchange,提问作者Adverbly

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 02:55:16