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

将变量推入数组返回undefined问题已解决:需指定索引

问题分析与解决办法

我来帮你拆解这个问题的核心,以及为什么用push时会出现undefined的情况:

先看你最初的“正常代码”

你这段代码其实并没有真正把对象存入数组,而是把原本声明为数组的变量appointmentArr直接重新赋值成了一个对象:

var inputStart = addAppointment.inputStart.value;
var inputEnd = addAppointment.inputEnd.value;
var appointmentArr = [];
// 这里把数组变量改成了单个对象,此时appointmentArr已经不是数组了
appointmentArr = {start:inputStart, end:inputEnd};
document.write(appointmentArr.start);
document.write(appointmentArr.end);

所以你能直接访问appointmentArr.start,本质是在访问一个对象的属性,而不是数组元素。

为什么用push会返回undefined?

你遇到的问题,核心是对数组的访问逻辑理解有误:数组是按索引存储的有序集合,当你用push把对象添加到数组后,必须通过数组索引来访问里面的对象,而不是直接给数组加属性。

比如你可能一开始错误地写了类似这样的代码:

var appointmentArr = [];
// 错误:直接给数组加属性,不是推入元素
appointmentArr.start = inputStart;
appointmentArr.end = inputEnd;
// 这时候访问appointmentArr.start虽然能拿到值,但数组本身是空的,用push的话逻辑不对

或者你用了push但访问时没加索引:

appointmentArr.push({start:inputStart, end:inputEnd});
// 错误:数组本身没有start属性,所以返回undefined
document.write(appointmentArr.start);

正确的push用法

要真正把对象存入数组并正确访问,应该这样写:

var inputStart = addAppointment.inputStart.value;
var inputEnd = addAppointment.inputEnd.value;
var appointmentArr = [];
// 使用push将对象添加到数组末尾,push会自动维护数组索引
appointmentArr.push({start:inputStart, end:inputEnd});
// 通过数组索引(从0开始)访问对应的对象,再取属性
document.write(appointmentArr[0].start);
document.write(appointmentArr[0].end);

这样appointmentArr始终是数组类型,后续还可以继续用push添加更多预约对象,比如appointmentArr.push({start: '14:00', end: '15:00'}),然后通过appointmentArr[1].start访问第二个预约的开始时间。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:13:04