forEach不是函数错误 [英] forEach is not a function error

查看:211
本文介绍了forEach不是函数错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试使用foreach遍历JSON对象时出现此错误. 有人可以帮忙吗?

I get this error when I am trying to iterate through my JSON object with a foreach. Can someone help, please?

这是我的JS:

function dateTimeChecker() {
     $.ajax({
            "url": 'get-booked.php',
            "method": "get",
            "dataType": "text",
            "cache": false
        }).done(function(jBooked) {
            var jBookedDates=JSON.parse(jBooked);
            console.log(jBookedDates);
               jBookedDates.forEach(function(jB){
                    if (jB=="11/01/2016") {console.log("works");}else{console.log("doesn't");}
        })
      });
}

这是有问题的对象:

此外,我想知道如果有人愿意解释该如何遍历此对象. :)

Also, I am wondering how can i iterate over this object if someone cares to explain. :)

推荐答案

您收到的响应是JSON.您不能在普通对象上使用数组对象的方法forEach.您必须在以下位置使用 Object.keys() 用来获取可枚举的自身属性的上下文属于已解析的JSON,

The response that you are receiving is a JSON. You can't use an array object's method forEach over a plain object. You have to use Object.keys() at this context to retrieve the enumerable own properties belongs to the parsed JSON,

Object.keys(jBookedDates).forEach(function(jB){
 if (jB=="11/01/2016") {
    console.log("works");
 } else {
    console.log("doesn't");
 }
});

对于注释中的查询,您可以使用方括号表示法访问这些数组,

For your query in the comment, you can use bracket notation to access those arrays,

Object.keys(jBookedDates).forEach(function(jB){
  var arr = jBookedDates[jB];
  console.log(arr); //will print the array belongs to each property.
});

这篇关于forEach不是函数错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆