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

报错Uncaught TypeError: json.forEach is not a function,如何遍历学校名称?

问题解决:Uncaught TypeError: json.forEach is not a function

错误原因

你解析后得到的json是一个对象(不是数组),forEach是数组的专属方法,对象无法调用这个方法,所以触发了类型错误。
你的数据结构里,存储学校名称的数组是对象的schools属性,应该遍历这个数组,而非整个对象。

修正后的代码

let myJSON = { "name": "naam", 
    "schools" : [
        "silver stone"  , 
        "woodlands stone"  , 
        "patthar"
    ],
    "class" : 12 }

myJSON = JSON.stringify(myJSON) ; 
let json = JSON.parse(myJSON) ; 

// 遍历schools数组,直接获取每个学校名称
json.schools.forEach(school => {
     console.log(school);
     // 如果要展示在页面上,可替换为以下代码(示例)
     // document.body.insertAdjacentHTML('beforeend', `<p>${school}</p>`);
});

补充说明

如果要在页面上展示学校名称,把console.log(school)替换成页面元素操作即可,比如用insertAdjacentHTML往页面中添加标签,就能直观看到学校列表。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 10:15:50