如何在JavaScript中通过变量与字符串拼接获取对应变量容器?
解决方法:用对象映射统一管理类型属性
直接零散定义grassStrong、fireWeak这类变量的方式,不仅容易污染全局作用域,还不利于维护。更稳妥的做法是把所有类型相关的属性集中放到一个对象里,通过字符串拼接的键名来访问:
// 把所有类型的Strong/Weak列表统一存到一个对象里 const typeMatchups = { grassStrong: ["water", "ground", "rock"], grassWeak: ["fire", "ice", "poison"], fireStrong: ["grass", "ice", "bug"], fireWeak: ["water", "ground", "rock"], // 可以继续添加其他类型的属性 }; const type = "grass"; // 通过字符串拼接键名,直接获取对应列表 console.log(typeMatchups[type + "Strong"]); // 输出 ["water", "ground", "rock"] console.log(typeMatchups[type + "Weak"]); // 输出 ["fire", "ice", "poison"]
如果你非得使用全局变量的方式(不推荐),在浏览器环境里可以通过window对象访问:
type = "grass"; grassStrong = ["water", "ground", "rock"]; console.log(window[type + "Strong"]);
Node.js环境则用global对象替代window,但这种方式会让变量暴露在全局,容易引发命名冲突,不建议在实际项目中使用。
内容的提问来源于stack exchange,提问作者ReinkDesigns
相关产品推荐
相关产品推荐

