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?

5
  • 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? Commented Dec 2, 2013 at 11:11
  • Internally, sparse Array keys are handled as String. Commented Dec 2, 2013 at 11:16
  • @Teemu - updated, sorry. Commented Dec 2, 2013 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 for..in to iterate an array, use regular for loop or for..each or what ever else loop purposed to iterate arrays. Commented Dec 2, 2013 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. 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! Commented Dec 2, 2013 at 12:17

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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 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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.