我有一个JSON对象,由AJAX请求返回,我有一些问题与.length,因为它一直返回未定义。只是想知道我是否用对了:
console.log(data.length);
console.log(data.phones.length);
它们都返回undefined,尽管它们是有效的对象。
更新:
返回的JSON对象示例:
{"reqStatus":true,"phones":{"one":{"number":"XXXXXXXXXX","type":"mobile"},"two":{"number":"XXXXXXXXXX","type":"mobile"}}}
您的问题是,电话对象没有长度属性(除非您在返回的JSON中定义了它),因为对象与数组不相同,即使用作关联数组。如果电话对象是一个数组,它将有一个长度。你有两个选择(也许更多)。
Change your JSON structure (assuming this is possible) so that 'phones' becomes
"phones":[{"number":"XXXXXXXXXX","type":"mobile"},{"number":"XXXXXXXXXX","type":"mobile"}]
(note there is no word-numbered identifier for each phone as they are returned in a 0-indexed array). In this response phones.length will be valid.
Iterate through the objects contained within your phones object and count them as you go, e.g.
var key, count = 0;
for(key in data.phones) {
if(data.phones.hasOwnProperty(key)) {
count++;
}
}
如果你只针对新的浏览器,选项2可能是这样的
var json=[{"id":"431","code":"0.85.PSFR01215","price":"2457.77","volume":"23.0","total":"565.29"},{"id":"430","code":"0.85.PSFR00608","price":"1752.45","volume":"4.0","total":"70.1"},{"id":"429","code":"0.84.SMAB00060","price":"4147.5","volume":"2.0","total":"82.95"},{"id":"428","code":"0.84.SMAB00050","price":"4077.5","volume":"3.0","total":"122.32"}]
var obj = JSON.parse(json);
var length = Object.keys(obj).length; //you get length json result 4