如何通过变量访问JavaScript对象?代码报错求助
问题解决:通过变量访问JavaScript对象属性
你遇到的问题核心是对象属性访问方式的误用:
- 点符号(
.)只能用于访问字面量形式的属性名(比如powerups.pizza),当你写powerups.food时,JavaScript会去powerups里找名为"food"的固定属性,而不是读取变量food存储的字符串值对应的属性,因此得到undefined,自然无法读取[0]。
解决方案1:改用方括号语法访问属性
把报错的代码行改成:
println(powerups[food][0]);
方括号语法支持用变量或表达式作为属性名,这样就能正确匹配随机生成的food值对应的对象属性。
额外问题:属性名不匹配
另外注意你的foodOptions数组里有一项是"finger",但powerups对象里对应的属性是"the finger",这会导致随机到"finger"时,powerups[food]依然是undefined,同样触发报错。需要把foodOptions里的"finger"修正为"the finger":
let foodOptions = ["pizza", "cupcake", "goblin soup", "the finger", "pasta"]
修正后的完整代码
let powerups = { "pizza":["You gained super strength!"], "cupcake":["You gained super speed!"], "goblin soup":["You turned into a goblin!"], "the finger":["Nothing happened!"], "pasta":["You are now super flexible!"] }; let foodOptions = ["pizza", "cupcake", "goblin soup", "the finger", "pasta"] function foodWheelManager(list) { println("Spinning wheel.") let food = foodOptions[Math.floor(Math.random()*foodOptions.length)]; println("You eat the " + food + "."); println(powerups[food][0]); println("Game over you won!"); }
内容的提问来源于stack exchange,提问作者Anthony Wright
相关产品推荐
相关产品推荐

