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

高校Quiz游戏开发:实现前十排行榜遇Uncaught TypeError错误求助

问题分析与解决

这个报错Uncaught TypeError: topTenAux.push is not a function的核心原因很明确:topTenAux不是数组类型,所以它没有push方法。结合你的代码来看,主要是两个问题导致的:

1. 存储到localStorage的内容错误

你代码的最后一行是这样的:

localStorage.setItem("topTenList", JSON.stringify(data));

这里你把单个data对象存进了localStorage,而不是完整的排行榜数组。下次读取时,JSON.parse解析出来的就是单个对象,不是数组,自然无法调用push方法。

2. 缺乏数据格式校验

如果localStorage里的topTenList被意外存成了非数组格式(比如字符串、单个对象),也会触发同样的错误,所以我们需要增加格式校验来兜底。

修正后的完整代码

var topTen = [];
var data = { "name": localStorage.getItem("topTenPlayer"), "points": pontos };
var topTenAux = [];

// 读取本地存储并做格式校验
const storedTopTen = localStorage.getItem("topTenList");
if (storedTopTen == null) {
  topTen.push(data);
} else {
  topTenAux = JSON.parse(storedTopTen);
  // 确保解析后是数组,否则重置为空数组
  if (!Array.isArray(topTenAux)) {
    topTenAux = [];
  }
  topTenAux.push(data);
}

// 存储完整的排行榜数组(而非单个对象)
const finalTopTen = storedTopTen ? topTenAux : topTen;
// 可选:按分数从高到低排序,只保留前10名
finalTopTen.sort((a, b) => b.points - a.points);
const sortedTopTen = finalTopTen.slice(0, 10);

localStorage.setItem("topTenList", JSON.stringify(sortedTopTen));
console.log(sortedTopTen);

额外说明

  • 我加了排行榜排序和截取逻辑,这样每次新增玩家数据后,都会自动按分数从高到低排序,只保留前10条数据,完美契合你的前十排行榜需求。
  • 增加的数组校验逻辑,能避免因为本地存储数据损坏导致的报错,让代码更健壮。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:10:16