如何在JSON中表示稀疏数组? [英] How to represent a sparse array in JSON?

查看:233
本文介绍了如何在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
}

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

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中表示稀疏数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆