最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - JSON implementations that handle sparse arrays - Stack Overflow

programmeradmin1浏览0评论

I need to know if any JSON implementations can handle sparse arrays to my satisfaction. I've seen the question: How to represent a sparse array in JSON? but using an object rather than an array is not an option for me; I need an array.

My minimum requirement would be that the implementation fill in any gaps with "undefined". Otherwise I am writing defensive code that fills in the gaps myself, before JSON encoding.

I need to know if any JSON implementations can handle sparse arrays to my satisfaction. I've seen the question: How to represent a sparse array in JSON? but using an object rather than an array is not an option for me; I need an array.

My minimum requirement would be that the implementation fill in any gaps with "undefined". Otherwise I am writing defensive code that fills in the gaps myself, before JSON encoding.

Share Improve this question edited May 23, 2017 at 12:13 CommunityBot 11 silver badge asked Apr 16, 2010 at 19:04 DexygenDexygen 12.6k13 gold badges86 silver badges151 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

Not possible. Forget implementations, it's just plain not allowed in the spec.

http://json/

Arrays are defined by value only. Objects are for when the index/key has meaning.

Could you use an object where the property name was an index and the property value was the value, then run it through an intermediary function to create your sparse array?

function getSparseArray(obj) {
  var ary = [];
  for (prop in obj) {
    var i = parseInt(prop,10);
    if (!isNaN(i)) {
      ary[i] = obj[prop];
    }
  }
  return ary;
}

You would send it something like

{ "5":"Five", "11":"Eleven", "99":"Ninety-Nine"}

and get back an array that was populated with just three values:

ary[5] = "Five"
ary[11] = "Eleven"
ary[99] = "Ninety-Nine"
ary[0] = 'undefined'
ary[98] = 'undefined'
etc.

ary here would have a length of 100, but it would be a "sparse" array in your sense.

发布评论

评论列表(0)

  1. 暂无评论