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

如何将函数参数作为对象键名调用对应对象方法?

动态调用对象中存储的函数

你当前写的commands.currentValue()是把currentValue当成了对象的固定键名,而非变量参数。要实现用函数参数作为键名调用对应函数,得用方括号语法——它支持通过动态值来获取对象属性。

正确写法

function changeText(currentValue) {
  // 用方括号获取对应键的函数并执行
  commands[currentValue]();
}

可选的安全处理

如果担心传入不存在的键导致报错,可以先做个存在性判断:

function changeText(currentValue) {
  const targetFn = commands[currentValue];
  // 确认是有效函数再调用
  if (typeof targetFn === 'function') {
    targetFn();
  } else {
    consoleDialog('无效命令');
  }
}

这样当currentValue等于help时,就会执行commands.help();等于ls时则执行commands.ls()。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 03:45:39