为何在异步函数中无法向空数组push数据,提示data.push不是函数?
解决
data.push is not a function报错问题 错误原因
你在全局声明了数组data,但在getUserData函数内部又用const data = await response.json()重新声明了同名变量,直接覆盖了全局的数组data。而接口返回的data是一个普通对象(结构为{results: [...]}),对象没有push方法,调用data.push()时自然触发类型错误。
修复方案
- 重命名函数内部接收接口响应的变量,避免和全局变量冲突;
- 根据需求调整
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
相关产品推荐
相关产品推荐

