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

如何根据变量值调用对应名称的函数?window调用报错undefined

问题解决方法

错误原因

你当前的called_function变量存储的是随机数组索引(0/1/2),而非possible_strings数组里的函数名字符串("a"/"b"/"c")。全局函数是以函数名作为键挂载在window上的,用数字索引去查找自然找不到对应函数,所以会报错undefined。

解决方式

方式一:修正变量取值逻辑

直接从possible_strings数组中取出对应的函数名字符串,再通过window调用:

function a() { alert('You called the a function.'); }
function b() { alert('You called the b function'); }
function c() { alert('You called the c function'); }

const possible_strings = ["a", "b", "c"];
// 改为从数组中取对应字符串,而非索引数字
const called_function = possible_strings[Math.floor(Math.random() * possible_strings.length)];
window[called_function](); // 正常执行

方式二:用对象管理函数(更推荐)

避免污染全局作用域,把函数集中放在一个对象里,直接通过对象属性调用:

// 用对象封装所有目标函数
const funcMap = {
  a: () => alert('You called the a function.'),
  b: () => alert('You called the b function'),
  c: () => alert('You called the c function')
};

const possible_keys = ["a", "b", "c"];
const targetKey = possible_keys[Math.floor(Math.random() * possible_keys.length)];
funcMap[targetKey](); // 调用对应函数

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 18:52:04