返回 JSON 对象的元素数量

发布于 2024-12-13 00:58:59 字数 397 浏览 3 评论 0原文

我需要迭代 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

甜扑 2024-12-20 00:58:59

您可以控制 JSON 数据吗?长度返回 1,因为数组中只有一个元素。这是因为 JSON 数据的构造方式所致。如果您想要更容易迭代的东西,您可能需要这样的东西:

this.worldData = [
                     {"1":"0","2":"0"},
                     {"1":"0","2":"0"},
                     {"1":"0","2":"0"}
                 ]

请注意,对象(用 {} 表示)没有 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:

this.worldData = [
                     {"1":"0","2":"0"},
                     {"1":"0","2":"0"},
                     {"1":"0","2":"0"}
                 ]

Note that objects (denoted with {}) don't have a length property, while arrays (denoted with []) do.

梦里的微风 2024-12-20 00:58:59

您将所有对象包装在一个对象内(第一个和最后一个花括号)。试试这个:

this.worldData =[
  {"0":{"1":"0", "2":"0"}},
  {"1":{"1":"0", "2":"0"}},
  {"2":{"1":"0", "2":"0"}}
];

jsFiddle 示例

You're wrapping all of your objects inside a single object (the first and last curly braces). Try this:

this.worldData =[
  {"0":{"1":"0", "2":"0"}},
  {"1":{"1":"0", "2":"0"}},
  {"2":{"1":"0", "2":"0"}}
];

jsFiddle example.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文