1

This answer says that the best way to iterate over sparse arrays is to use for X in Array

However, when I tried this I tripped up because the type of X was a string, rather than the integer index I was expecting. (All fine until I added it to another integer...)

var arr = [];
arr[10000] = "Hello";

var shifted = []

for (var x in arr)
    shifted[10+x] = arr[x];

"Expected":

  shifted[10010] = "Hello

Actual

  shifted["1010000"] = "Hello" 

Is there a better way of iterating a sparse array using the index, or should I just use Number(X) where required?

Community
  • 1
  • 1
Roddy
  • 66,617
  • 42
  • 165
  • 277
  • 3
    In that post they are iterating objects, not arrays... Can you show an example of your array, and tell us what you actually want to do? – Teemu Dec 02 '13 at 11:11
  • Internally, sparse `Array` keys are handled as `String`. – Florent Dec 02 '13 at 11:16
  • @Teemu - updated, sorry. – Roddy Dec 02 '13 at 11:23
  • 2
    LOL, this has nothing to do with a sparse array. You're just concatenating a string to a number, and use that string as a new key. The teach of a lesson: [Never use](http://stackoverflow.com/questions/500504/why-is-using-for-in-with-array-iteration-such-a-bad-idea) `for..in` to iterate an array, use regular `for` loop or `for..each` or what ever else loop purposed to iterate arrays. – Teemu Dec 02 '13 at 12:00
  • @Teemu, Well, if the array wasn't sparse I'd be using a vanilla for loop which avoids the problem. But for a sparse array that's not going to work. I'm more aware now of the `for in` pitfalls, and how to avoid them. http://stackoverflow.com/a/9329476/1737 . `.forEach` Looks the best approach, but I just need to remember that array keys are actually strings. Carve it on my tombstone! – Roddy Dec 02 '13 at 12:17

1 Answers1

1

This is how V8 (and others JavaScript engines) handles arrays:

V8 uses two different methods to handle arrays:

  • Fast elements:
    Designed for arrays where set of keys are very compact. They have a linear storage buffer that can be accessed very efficiently.

  • Dictionary elements:
    Designed for sparse arrays which don’t have every elements inside of them. It is actually a hash table, more expensive to access than “Fast Elements”

Source: http://thibaultlaurens.github.io/javascript/2013/04/29/how-the-v8-engine-works/

When you are using a sparse array, the key is converted to string and then hashed. If you want numeric keys: don't use a sparse array or manually convert the key to a number.

Community
  • 1
  • 1
Florent
  • 12,310
  • 10
  • 49
  • 58
  • Thanks. But if the array is not sparse, is the key still going to come back as a string in my `for X in Array`? – Roddy Dec 02 '13 at 12:01
  • @Roddy No. When you use `for in` you are iterating through the object properties. A property is always a string. So even if your array is not sparse, `for in` will return strings. – Florent Dec 02 '13 at 13:15