我正在尝试迭代p
并选择一个网址
p = {
"photos":[
{"alt_sizes":[{"url":"img1.png"}]},
{"alt_sizes":[{"url":"img2.png"}]}
]
}
什么是最有效的获取方式"url"
?
编辑:"photos"
可以有两个以上的值,所以我需要迭代
我正在尝试迭代p
并选择一个网址
p = {
"photos":[
{"alt_sizes":[{"url":"img1.png"}]},
{"alt_sizes":[{"url":"img2.png"}]}
]
}
什么是最有效的获取方式"url"
?
编辑:"photos"
可以有两个以上的值,所以我需要迭代
试试这个:
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";
也可以使用 ECMAScript 5forEach
而无需额外的库。
var urls = []
p.photos.forEach(function(e) {
urls.push(e.alt_sizes[0]['url']);
});
console.log(urls);
使用 $.each。一个例子
$.each( obj, function( key, value ) {
alert( key + ": " + value );
if(typeof(value)=="object")
{
$.each( value, function( key, value ) {
alert( key + ": " + value );
});
}
});
// 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)
}
}
}
}