我有一个要在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中表示稀疏数组?
发布评论