Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/spring-mvc/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何打印此JSON对象的长度?_Javascript_Json - Fatal编程技术网

Javascript 如何打印此JSON对象的长度?

Javascript 如何打印此JSON对象的长度?,javascript,json,Javascript,Json,我试图将这个JSON对象的长度打印到控制台,但我一直收到“undefined” 这是用PHP进行JSON编码,然后通过ajax返回到一个匿名函数“msg” {"1":{"item_id":"shirt_straight--small","quantity":5},"2":{"item_id":"shirt_straight--medium","quantity":"2"}} 打印到控制台: console.log(msg.length); //undefined console.log(msg

我试图将这个JSON对象的长度打印到控制台,但我一直收到“undefined”

这是用PHP进行JSON编码,然后通过ajax返回到一个匿名函数“msg”

{"1":{"item_id":"shirt_straight--small","quantity":5},"2":{"item_id":"shirt_straight--medium","quantity":"2"}}
打印到控制台:

console.log(msg.length); //undefined
console.log(msg[1].item_id); //shirt_straight--small
我可以打印msg[1]的值。item_id,但无法通过msg.length获取长度

感谢您的帮助。

数组具有长度属性。默认情况下,对象不包含。我认为问题出在php端。。。您应该对数组进行编码并将其发送回。数组是零索引的,所以这可能是问题所在。也许json_encodearray_值$msg


如果你的关键点是正确的,那么给Object.keysmsg.length一个快照。

这可以是

看看公认的答案

顺便说一句,刚发现谷歌搜索javascript对象长度

编辑:


的确,对象没有length属性,您可以使用Object.keysfoobar.length获取长度,但它在IE8中不起作用

您可以使用Object.keysmsg.length您的JSON不是数组。对象没有有效的length属性.Object.keysmsg.length。谢谢