【发布时间】:2019-07-19 12:44:45
【问题描述】:
所以我试图将项目推送到数组中,尽管数组中有项目,但它似乎返回的长度为 0。
let calendarDates = []
async function getDates() {
const response = await fetch('/calendars/fetch_dates')
let res = await response.json()
res.forEach(el => {
calendarDates.push(el)
})
}
getDates()
createCalendar(date, side)
.
.
.
function createCalendar(date, side) {
console.log('createCalendar', calendarDates, "is array?", Array.isArray(calendarDates), 'length', calendarDates.length)
.
.
}
我的 console.log 正在打印 calendarDates 和 length : array
console.log 存在于一个单独的函数中
那么为什么它返回 0 的长度? 当尝试控制台记录一个 forEach 循环时,也没有任何返回,所以我不认为浏览器显示错误的乐趣值
【问题讨论】:
-
你把你的
console.log放在哪里? -
@YongQuan 更新了我的代码 sn-p 以显示控制台日志的位置
-
getDates 是一个异步函数,而 createCalendar 是一个同步函数。因此 createCalendar 将首先被调用,并在 getDates 函数获取异步数据之前尝试读取数组的长度。
-
我相信您所看到的不一致之处在于
console.log()的工作方式(至少在 Chrome 中)。createCalendar()在getDates完成之前被调用,但console.log()被延迟并使用calendarDates的后一个值...我不知道我是否解释正确.. 就像console.log计算参数但是因为 calendarDates 是一个数组,所以它是通过引用传递的。因此,您不能相信日志中的值与实际调用时的值相同。