For循环不适用于json数据

时间:2015-07-12 19:15:10

标签: javascript facebook-javascript-sdk

我正在尝试使用以下代码在javascript中创建循环。它从json数据中获取长度。 console.log(albums.data.length);行正在工作并返回3.为什么循环不起作用呢? console.log(x);没有返回任何内容,即使不是空行。 控制台也没有错误。

function getBestPhoto(albums){
    console.log(albums);
    console.log(albums.data.length);
    for(var x in albums.data.length){
        console.log(x);
        for(var y in albums.data[x].photos.length){
            console.log(y);
        }
    }
}

我尝试过其他类型的循环(for(var i = 0; i < blabla; i++)),但它也不起作用。

编辑: 我想用  for(var x = 0; x < albums.data.length; x++){ console.log(albums.data[x].photos.id); } 而不是

for(var x in albums.data){

我该怎么做?

2 个答案:

答案 0 :(得分:1)

您应该从循环中移除.length

function getBestPhoto(albums){
    console.log(albums);
    console.log(albums.data.length);
    for(var i = 0; i < albums.data.length; i++){
        var x = albums.data[i];
        console.log(x);
        for(var j = 0; j < albums.data[i].photos.length; j++){
            var y = albums.data[i].photos[j];
            console.log(y);
            console.log(albums.data[i].photos[j].id);
        }
    }
}

答案 1 :(得分:0)

for-in循环不适用于数组,而是用于迭代对象的属性/字段。如果albums.data是数组,则应使用forEach循环语句。如果albums.data是一个对象,并且您尝试访问其属性/字段/属性,则可以使用for-in构造。

如果albums.data是数组,请尝试:

albums.data.forEach(function(element, index) {
  // Here you have access to each element (object) of the "albums.data" array
  console.log(element.toString());
  // You can also access each element's properties/fields if the element is an 
  // object. 
  // If the element is an array itself, you need to iterate over its elements 
  // in another inner foreach. 
  // Here we are accessing the "photos" property of each element - which itself
  // is another array.
  element.photos.forEach(function(photo, index) {
    // Here you have access to the elements of the "photos" array 
    // Each element of the "photos" array is put in the photo variable. 
    // Assuming each element of the "photos" array is an object, you can access 
    // its properties, using the dot notation:
    console.log("photo id=", photo.id);
    // If the property name (e.g. "id") is not a valid javascript name 
    // (has some special symbols), use the bracket notation
    console.log("photo URL=", photo["photo-url"]);
  });
});

您也可以使用lodash库(以及许多其他功能)。

如果albums.data是对象,请尝试:

for (var prop in albums.data) {
  // Again, this construct is for accessing properties of an object 
  // (e.g. if albums.data is an object), not an array.
  console.log("property name=" + prop + ", " + "property value=" +
              albums.data[prop]);
}