返回 JSON 对象的元素数量
我需要迭代 JSON 对象中的每个元素,但我无法找到一种方法来计算该对象中的元素数量,以便我可以使用 for 循环进行迭代。这是我的对象:
this.worldData =[
{"0":{"1":"0", "2":"0"},
"1":{"1":"0", "2":"0"},
"2":{"1":"0", "2":"0"}}
];
我正在尝试:
alert(this.worldData.length);
问题是,无论我在 JSON 对象中放入多少元素,它总是返回 1
。
I need to iterate over every element in a JSON object, and I'm having trouble working out a way to count the number of elements in that object so I can use a for loop to iterate. Here's my object:
this.worldData =[
{"0":{"1":"0", "2":"0"},
"1":{"1":"0", "2":"0"},
"2":{"1":"0", "2":"0"}}
];
And what I'm trying:
alert(this.worldData.length);
Problem is, it always returns 1
, no matter how many elements I put into the JSON object.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以控制 JSON 数据吗?长度返回 1,因为数组中只有一个元素。这是因为 JSON 数据的构造方式所致。如果您想要更容易迭代的东西,您可能需要这样的东西:
请注意,对象(用
{}
表示)没有 length 属性,而数组(用[] 表示)
) 做。Do you have control over the JSON data? The length is returning 1 because there is only one element in the array. This is because of the way the JSON data is structured here. If you want something easier to iterate over, you would want something like this:
Note that objects (denoted with
{}
) don't have a length property, while arrays (denoted with[]
) do.您将所有对象包装在一个对象内(第一个和最后一个花括号)。试试这个:
jsFiddle 示例。
You're wrapping all of your objects inside a single object (the first and last curly braces). Try this:
jsFiddle example.