如何获取json返回数据的长度并运行for循环

时间:2016-11-10 12:41:07

标签: javascript php json ajax

我有这个ajax调用,其结果是json格式

$.ajax({
    url: link,
    dataType: "json",
    success: function(data){
        console.log(data); //C.L-1
        console.log(data.length); //C.L-2
    }
})

这是结果

$users_arr = array();
//After a successful query from my database
While($sql = mysqli_fetch_array($query)){
    $user_id = $sql['id'];
    $user_age = $sql['age'];
    $user_name = $sql['name'];
    $users_arr[$user_id] = $user_id.','.$user_name.','.$user_age;
}
echo json_encode($users_arr);

现在C.L-1返回true但C.L-2返回undefined。我认为返回的data是一个自己的数组,所以我想为每个用户运行一个for循环

for(var i = 0; data.length > i; i++){
    eachUser = data[i];
    userInfo = eachUser.split(',');
    userId = userInfo[0]; // and so on for the other info
    $('div#age'+userId).html(userAge);
}

但问题是data.length返回undefined,这阻止了我运行for循环。请给我更好的帮助?

编辑以下是来自C.L-1

的一些数据
Object {8: "8,debbie,23", 3: "3,doggie,20", 7: "7,dini,22"}

1 个答案:

答案 0 :(得分:2)

使用简单的for ... in循环:



var obj = {
  7: "8,debbie,23",
  8: "3,doggie,20",
  9: "7,dini,22"
};

for(var x in obj){
  console.log(obj[x]);
}




for in循环的替代方法可以是:



var obj = {
  7: "8,debbie,23",
  8: "3,doggie,20",
  9: "7,dini,22"
};

Object.keys(obj).forEach(function(key) {
    console.log(key, obj[key]);
});




重要的是要知道,只有keys0开始才能使用下两个选项。

您可以像这样计算对象中的元素:



var obj = {
  0: "8,debbie,23",
  1: "3,doggie,20",
  2: "7,dini,22"
};
var wrong_count = obj.length; //this will return undefined
var correct_length = Object.keys(obj).length; //this will return 3
console.log(wrong_count);
console.log(correct_length);

for(var i = 0; i < correct_length; i++){
  console.log(obj[i]);
}
&#13;
&#13;
&#13;

有关Object.keys()的详细信息,请参阅此link

另一种替代方法是使用for in循环:

&#13;
&#13;
var obj = {
  0: "8,debbie,23",
  1: "3,doggie,20",
  2: "7,dini,22"
};

var another_count = 0;
for(var x in obj){
	another_count++;
}
console.log(another_count);

for(var i = 0; i < another_count; i++){
  console.log(obj[i]);
}
&#13;
&#13;
&#13;