【问题标题】:Cannot read property 'forEach' of undefined in reactjs application无法读取 reactjs 应用程序中未定义的属性“forEach”
【发布时间】:2018-02-06 08:41:38
【问题描述】:

我有一个 JS 方法,它接受一个 JSON 文件并尝试从中获取信息:

getData(json) {
        var output = '';

        json.Legs.forEach(function (item) {
            .
            .
            .
            .
            .
            .
        });

        return output;
    }

forEach 出现此错误:

未捕获的类型错误:无法读取未定义的属性“forEach”

是否可以像这样使用 forEach 或者我根本不应该使用 forEach? 有没有其他方法可以做到这一点?

【问题讨论】:

  • 错误很清楚,json.Legs 中没有数据。
  • 根据定义,JSON 没有任意属性,因为它只是一个字符串。你的意思是一个 JavaScript 对象,还是你传递一个字符串?你怎么称呼那个函数?
  • 只有在检查 json.Legs 不为空时才需要运行每个循环。例如 if(!json.Legs){ json.Legs.forEach(function (item) { . . . . . . . . }); }

标签: javascript json foreach


【解决方案1】:

确认json.Legs不为空后,需要执行循环。例如

if(json.Legs){
  json.Legs.forEach(function (item) {
            .
            .
            .
            .
            .
            .
        });
}

【讨论】:

    【解决方案2】:

    将此添加为代码的第一行,然后查看打印的内容。如果它是一个数组,你可以在上面全部forEach。否则它会抛出正确的错误。

    console.log(json.Legs)
    

    【讨论】:

    • 鉴于错误信息,显然不是数组而是undefined ;)
    • 它返回未定义!
    • 然后检查输入json变量的内容。它需要有Legs 属性才能工作。
    • 简洁的答案 :) 但我认为 json 应该是 caps JSON
    【解决方案3】:

    这样的事情应该可以解决问题(在迭代之前检查 .legs 属性是否存在以及它是否是一个数组):

    getData(json) {
        var output = '';
    
        if(json.Legs && Array.isArray(json.Legs)){
    
         json.Legs.forEach(function (item) {
            //do something with item
         });
        }
    
        return output;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-03
      • 1970-01-01
      • 2020-04-23
      • 2016-08-08
      • 2018-12-16
      • 1970-01-01
      相关资源
      最近更新 更多