如何在JSON中表示稀疏数组?

编程入门 行业动态 更新时间:2024-10-27 08:30:22
本文介绍了如何在JSON中表示稀疏数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个要在JSON中表示的稀疏数组.例如:

I've got a sparse array that I want to represent in JSON. For example:

-10 => 100 -1 => 102 3 => 44 12 => -87 12345 => 0

我该怎么做?我可以这样做吗?

How can I do this? Can I do this?

推荐答案

您可以将其表示为简单的对象:

You can represent it as a simple object:

{ "-10" : 100, "-1" : 102, "3" : 44, "12" : -87, "12345" : 0 }

由于它将是一个简单的对象,因此无法以与数组相同的方式对其进行迭代,但是可以使用 for...in 语句:

Since it will be a simple object, you cannot iterate it the same way as an array, but you can use the for...in statement:

for (var key in obj) { if (obj.hasOwnProperty(key)) { var value = obj[key]; } }

如果您想通过键访问特定元素,也可以在此处使用方括号属性访问器:

And if you want to access an specific element by key, you can use also here the square bracket property accessor:

obj['-10']; // 100

请注意,我在内部使用了 hasOwnProperty 方法 for...in 循环中,这是为了防止迭代在较高级别的原型链上定义的属性,这可能会导致问题和意外行为...更多信息此处.

Note that I use the hasOwnProperty method inside the for...in loop, this is to prevent iterating properties defined on higher levels of the prototype chain, which can cause problems and unexpected behavior... more info here.

更多推荐

如何在JSON中表示稀疏数组?

本文发布于:2023-10-20 03:42:21,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1509735.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:稀疏   数组   如何在   JSON

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!