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

JavaScript数组能否使用间接寻址?如何通过变量访问对象属性

问题解答

你的需求是可行的,但不能用你写的inventory[1].indirectaddress这种点语法,得用方括号访问符来实现间接属性访问。

原因说明

JavaScript里,点语法(.)后面跟的是固定的属性名字面量,比如inventory[1].products.books里的books是直接写死的属性名。而如果你想用变量来指定要访问的属性,必须用方括号[]——方括号里可以放变量、字符串或者任何能返回属性名的表达式。

修正后的代码示例

假设你的inventory结构是这样的:

const inventory = [
  {},
  {
    products: {"itemid":"na", "books":10, "dvds":15, "cds":4}
  }
];

按照你的需求,正确的代码应该是:

// 设置itemid为"books"
inventory[1].products.itemid = "books";
// 把itemid的值存到变量里
const indirectaddress = inventory[1].products.itemid;
// 用变量间接访问books属性
const numberofbooks = inventory[1].products[indirectaddress];

console.log(numberofbooks); // 输出:10

关键要点

  • 如果你要通过变量动态访问对象属性,一定要用对象[变量名]的格式,而不是对象.变量名
  • 注意原代码里的小细节:itemid是在products对象内部的,所以要写成inventory[1].products.itemid,而非inventory[1].itemid

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 01:05:17