0

我正在尝试迭代p并选择一个网址

p = {
     "photos":[
         {"alt_sizes":[{"url":"img1.png"}]},
         {"alt_sizes":[{"url":"img2.png"}]}
     ]
}

什么是最有效的获取方式"url"

编辑"photos"可以有两个以上的值,所以我需要迭代

4

4 回答 4

4

试试这个:

function forloop(){
    var arr = p.photos, url , array_of_urls = [];
    for(var i=0; i < arr.length; i++){
       url = arr[i].alt_sizes[0]['url'];
      array_of_urls .push(url);
    }
    console.log(array_of_urls, url)
    return url;
  }

var bigString = "something"+forloop()+"something";
于 2013-04-23T20:05:07.807 回答
2

也可以使用 ECMAScript 5forEach而无需额外的库。

var urls = []
p.photos.forEach(function(e) {
    urls.push(e.alt_sizes[0]['url']);
});
console.log(urls);
于 2013-04-23T20:07:37.797 回答
-1

使用 $.each。一个例子

 $.each( obj, function( key, value ) {
 alert( key + ": " + value );

  if(typeof(value)=="object")
  {
    $.each( value, function( key, value ) {
         alert( key + ": " + value );
      });
  }
});
于 2013-04-23T20:06:05.860 回答
-1
// loop through all properties of `p` (assuming that there might be other objects besides
// `photos` that might have the `url` property we are looking for)
for(i in p){
  // ensure the property is not on the prototype
  if (p.hasOwnProperty(i)) {
    // loop through the array
    for(j = p[i].length; j--;){
      // check that the `url` property is there
      if(typeof p[i][j].alt_sizes[0].url != "undefined"){
        // do something with the url propert - in this case, log to console
        console.log(p[i][j].alt_sizes[0].url)
      }
    }
  }
}
于 2013-04-23T20:11:11.247 回答