我有如下json数据:
{
"comment_ds": [
{
"c_user": [
"Bob",
"Bob",
"Bob",
"Bob",
"Bob"
],
"c_user_img": [
"/media/accounts/1809094310/1809094310.jpg",
"/media/accounts/1809094310/1809094310.jpg",
"/media/accounts/1809094310/1809094310.jpg",
"/media/accounts/1809094310/1809094310.jpg",
"/media/accounts/1809094310/1809094310.jpg"
],
"c_content": [
"nice",
"awesome",
"very cool",
"great",
"perfect"
]
}
]
}
我使用ajax响应的这一部分来呈现数据:
success: function(data) {
comm_data = data['comment_ds'][0];
var i = 0;
Object.entries(comm_data).forEach(([key, value]) => {
if (i < value.length){
c_user = comm_data["c_user"][i];
c_content = comm_data["c_content"][i];
c_user_img = comm_data["c_user_img"][i];
comment = document.createElement('tr');
comment.setAttribute('class','comment')
$(comment).html(`
<th class="comm_th_1"><img class="comm_user_image" src="${c_user_img}"><a class="comm_user">${c_user}</a></th>
<th class="comm_th_2">${c_content}</th>
<th class="comm_th_3"></th>`);
$('.comm_cont').append(comment);
}
i+=1;
});
}
}
它适用于前3条评论,但随后停止。
当我console.logvalue.length
时,我得到5,但i
在3时停止递增。
感谢您的任何建议
您可以使用forEach
方法通过c_user
属性进行循环。此方法支持索引器。
由于c_user
、c_user_img
和c_content
具有相同的大小,因此可以使用该索引来分配其他值:c_user_img
c_content
:
var data = {
"comment_ds": [
{
"c_user": [
"Bob",
"Bob",
"Bob",
"Bob",
"Bob"
],
"c_user_img": [
"/media/accounts/1809094310/1809094310.jpg",
"/media/accounts/1809094310/1809094310.jpg",
"/media/accounts/1809094310/1809094310.jpg",
"/media/accounts/1809094310/1809094310.jpg",
"/media/accounts/1809094310/1809094310.jpg"
],
"c_content": [
"nice",
"awesome",
"very cool",
"great",
"perfect"
]
}
]
};
comm_arr = data['comment_ds'];
comm_data = comm_arr[0];
comm_data.c_user.forEach(function (user, index) {
img = comm_data.c_user_img[index];
content = comm_data.c_content[index];
console.log(user, img, content);
});