【问题标题】:Cannot access JavaScript Objects in Array无法访问数组中的 JavaScript 对象
【发布时间】:2020-03-17 04:29:21
【问题描述】:

目前,我在函数外部初始化了一个名为约会的列表,我的代码正在从该函数内将对象推送到该数组中。

var appointments = [];
async function getAllAppointmentEvents() {
    var doctorList = await getAllDoctors();
    // For all doctors
    for (let i = 1; i < doctorList["doctorinfo"].length; i++) {
        // Find their appointments
        schedule = await getAppointmentsByDoctor(i).then(function (response) { return response; });
        // For each appointment
        if (schedule["schedules"] !== undefined) {
            for (let j = 0; j < schedule["schedules"].length; j++) {
                var startDate = new Date(schedule["schedules"][j]["datetime"]);
                // startDate = new Intl.DateTimeFormat("")
                var endDate = new Date(schedule["schedules"][j]["datetime"]);
                endDate.setHours(startDate.getHours() + 1);
                var result = {
                    title: doctorList["doctorinfo"][i][1],
                    start: startDate.toISOString().slice(0, 19),
                    end: endDate.toISOString().slice(0, 19),
                    color: "#C0C0C0",
                    groupId: doctorList["doctorinfo"][i][0]
                };
                appointments.push(result);
            }
        }
    }
}

当我 console.log 输出时,我得到一个似乎包含所有对象的空数组。但我无法通过appointments[0] 访问这些对象。我也试过打印出Object.keys(appointments),它也没有任何键。当我在函数内使用 console.log 时,可以正常访问该数组。

当我从函数外部 console.log 列表时得到的输出:output

我需要帮助从函数外部访问对象。谢谢!

【问题讨论】:

  • 您需要发布代码以尝试解决问题。
  • 发布您的代码,以便有机会快速回答。
  • 嗨!您是指整个文件吗?
  • 你在哪里声明appointments
  • 我在函数之外声明了约会!我已经更新了代码以显示这一点

标签: javascript jquery arrays ajax object


【解决方案1】:

您的第一个 for 循环是一个同步操作。在每个操作中,它将运行循环块内的操作,并进入下一次迭代(i++,并重复所有操作)。

在同步循环内部,你有一个异步操作:

schedule = await getAppointmentsByDoctor(i).then(function (response) { return response; }); 

同步循环不适用于您的异步操作 - 这可能是您的数组未在您预期的时间填满的原因。

您可以使用 Promise.all 的实现和当前的 async/await 来解决您的问题。

您还可以查找 asyncForEach 实现,例如 this articlein this gist

Gist 内容以防被删除:

const waitFor = (ms) => new Promise(r => setTimeout(r, ms))
const asyncForEach = async (array, callback) => {
  for (let index = 0; index < array.length; index++) {
    await callback(array[index], index, array)
  }
}

const start = async () => {
  await asyncForEach([1, 2, 3], async (num) => {
    await waitFor(50)
    console.log(num)
  })
  console.log('Done')
}

start()

【讨论】:

  • 在给出 -1 时,如果您解释为什么这样做,您将能够帮助我不再重复同样的错误。
猜你喜欢
  • 2020-08-14
  • 2017-08-13
  • 2017-09-04
  • 2019-06-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多