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

如何构建带命名键的JavaScript数组结构?push方法使用困惑

实现方法

你可以通过两种方式实现这个需求,核心都是确保对象中指定键对应的值是数组,之后直接对这个数组调用push方法即可:

方式一:先初始化对象和数组,再逐步添加元素

先创建空对象,给目标键赋值空数组,之后直接通过对象的键访问数组并执行push:

// 创建空对象
const targetObj = {};
// 给对象添加"ExampleName"键,值设为空数组
targetObj.ExampleName = [];

// 向数组中push元素
targetObj.ExampleName.push({ id: 1, content: "第一个元素" });
targetObj.ExampleName.push({ id: 2, content: "第二个元素" });

// 最终结果:{ ExampleName: [ { id:1, ... }, { id:2, ... } ] }

方式二:先生成数组,再赋值给对象的键

如果已经通过push生成了完整的数组,直接把数组赋值给对象的对应键即可:

// 先通过push生成元素数组
const elementArray = [];
elementArray.push({ id: 1, content: "元素A" });
elementArray.push({ id: 2, content: "元素B" });

// 构建包含命名键的对象
const targetObj = {
  ExampleName: elementArray
};

本质上,你不需要特殊的push变种,只要能正确访问到对象里的数组,普通的数组push方法就完全适用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 11:51:32