我正在尝试使用以下代码在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);
        }
    }
}


我尝试了另一种类型的loop(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){


我该怎么做?

最佳答案

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]);
}

关于javascript - For循环不适用于json数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31371573/

10-12 06:59