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

为何在异步函数中无法向空数组push数据,提示data.push不是函数?

解决data.push is not a function报错问题

错误原因

你在全局声明了数组data,但在getUserData函数内部又用const data = await response.json()重新声明了同名变量,直接覆盖了全局的数组data。而接口返回的data是一个普通对象(结构为{results: [...]}),对象没有push方法,调用data.push()时自然触发类型错误。

修复方案

  1. 重命名函数内部接收接口响应的变量,避免和全局变量冲突;
  2. 根据需求调整push的内容(如果想添加单个用户对象,无需把newUser定义为数组)。

修正后的代码:

let data = [];
async function getUserData() {
     const response = await fetch('https://randomuser.me/api');
     // 重命名变量,避免覆盖全局data
     const apiData = await response.json();
     const user = apiData.results[0];

     // 将newUser定义为单个对象(而非数组)
     const newUser = {
        name: `${user.name.title} ${user.name.first}`,
        money: Math.floor(Math.random()*1000000),
      };

    // 往全局数组data中添加单个对象
    data.push(newUser);
    // 如果坚持要保留newUser为数组,可用扩展运算符展开后添加:
    // data.push(...newUser);
}

getUserData();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 10:07:16