Javascript:array.length返回undefined [英] Javascript : array.length returns undefined
问题描述
我有一组由PHP的 json_encode
函数传递的数据。我正在使用jQuery getJSON
函数对其进行解码:
I have a set of data that is being passed on by the PHP's json_encode
function. I'm using the jQuery getJSON
function to decode it:
$.getJSON("url", function (data) {
console.log(data);
});
控制台中的输出如下所示:
The output looks like this in the console:
Object {1: Object, 2: Object, 3: Object, 4: Object, 5: Object, 6: Object, 7: Object, 8: Object, 9: Object, 10: Object}
我可以使用数据访问每个数组[1]
, data [2]
等,但是为了让它更容易我想到循环,所以我可以一次访问所有:
I can access each array by using data[1]
, data[2]
etc, but to make it easier I thought of looping thought it so I can access all at once:
$.getJSON("url", function (data) {
for (var i = 0, len = data.length; i < len; i++) {
//do something
}
});
但是我无法使用它,因为 data.length
返回值 undefined
。有什么问题,如何解决?
However I can't get this to work because the data.length
returns the value undefined
. What is wrong and how can I fix it?
推荐答案
对象没有 .length
property。
Objects don't have a .length
property.
一个简单的解决方案,如果你知道你不必担心 hasOwnProperty
检查,就是这样做:
A simple solution if you know you don't have to worry about hasOwnProperty
checks, would be to do this:
Object.keys(data).length;
如果 支持IE 8或更低版本,你将拥有改为使用循环:
If you have to support IE 8 or lower, you'll have to use a loop, instead:
var length= 0;
for(var key in data) {
if(data.hasOwnProperty(key)){
length++;
}
}
这篇关于Javascript:array.length返回undefined的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!