使用循环在javascript中处理json数组
我有这样的json数组:使用循环在javascript中处理json数组,javascript,php,arrays,json,Javascript,Php,Arrays,Json,我有这样的json数组: {"error":false, "message":"", "Album_list":[{"Album":{"id":"27","user_id":"46","title":"Internal","status":"1","time":"","created":"2016-05-02 17:20:27","modified":"2016-05-02 17:20:27"}}, {"Album":{"id":"30","user_id":"46","t
{"error":false,
"message":"",
"Album_list":[{"Album":{"id":"27","user_id":"46","title":"Internal","status":"1","time":"","created":"2016-05-02 17:20:27","modified":"2016-05-02 17:20:27"}},
{"Album":{"id":"30","user_id":"46","title":"efdrhty","status":"1","time":"","created":"2016-05-04 08:52:12","modified":"2016-05-04 08:52:12"}},
{"Album":{"id":"37","user_id":"46","title":"external","status":"1","time":"","created":"2016-05-06 08:04:55","modified":"2016-05-06 08:04:55"}},
{"Album":{"id":"38","user_id":"46","title":"James Jobs" ,"status":"1","time":"","created":"2016-05-17 09:40:41","modified":"2016-05-17 09:40:41"}},
{"Album":{"id":"41","user_id":"46","title":"17th May 2016","status":"1","time":"","created":"2016-05-17 10:20 :10","modified":"2016-05-17 10:20:10"}}]}
现在,在success
函数中,我需要循环中的Album\u列表
数据
我试过了,但没法正确地得到它
Javascript代码:
success: function (response) {
if (response.error == true) {
console.log(response.message);
} else {
content += '<div class="ui-grid-b gallery-sec">';
for (img in response.Album_list) {
console.log(img);
content += '<div class="ui-block-b gallery-sec">' +
'<div class="gallery-thumb-col">' +
'<div class="gallery-thumb">' +
'<img src="images/blue-box-logo.png" alt="">' +
'</div>' +
'<div class="full">' +
'<h2>'+img.Album.title+'</h2>' + //I need the title of album here
'</div>' +
'<p>2 Photos</p>' +
'<div class="ftr-bg">' +
'<i class="fa fa-trash-o" aria-hidden="true"></i></div>' +
'</div>' +
'</div>';
}
content += '</div>';
$('#gallery .page-content').html(content);
}
}
成功:功能(响应){
如果(response.error==true){
console.log(response.message);
}否则{
内容+='';
用于(img响应。相册列表){
控制台日志(img);
内容+=''+
'' +
'' +
'' +
'' +
'' +
''+img.Album.title+''+//我需要这里的相册标题
'' +
“2张照片”+
'' +
'' +
'' +
'';
}
内容+='';
$('#gallery.page content').html(content);
}
}
console.log(img)代码>给出0,然后是1,最后是4。但是我需要相册数组。使用此:
for (var i = 0; i < response.Album_list.length; i++) {
var album = response.Album_list[i];
console.log(album);
}
替换
for (img in response.Album_list) {
// code here
}
与
因为您的img
不是元素,而是索引的变量。您也可以尝试:
for (var index in response.Album_list) {
img = response.Album_list[index];
// rest of the code as it it
}
不要使用for for数组。如果可能的话,使用regular for i loop或forEach。我尝试了forEach循环,但它在javascriptLoop中不起作用。没关系,我只是想知道如何获取Album
arrayAlbum是一个对象。但并非所有浏览器都支持Check my answerforEach。但我认为它更干净,所以如果可能的话就使用它。如果订单很重要,就不要使用它。使用数组是因为顺序是相关的,而在中使用for不能确保它将按顺序循环!一般来说,不要使用for for数组。你太棒了。坚持下去。
response.Album_list.forEach(function (img) {
// code here
});
for (var index in response.Album_list) {
img = response.Album_list[index];
// rest of the code as it it
}