2

I have an array as follows:

levelinfoarray["test"] = new Array(16,20,4,5,"Test level");
levelinfoarray[1] = new Array(29,25,17,13,"Introduction");
levelinfoarray[2] = new Array(16,24,6,4,"Counting...");
levelinfoarray[3] = new Array(16,20,4,5,"Where am I going?");
...

I want to iterate through the array and get the level number and level description like this

Test) Test level
1) Introduction
2) Counting...
3) Where am I going?
...

I have tried a for loop and a forEach, but both only give me the numbered entries. How would I get the "test" entry?

1
  • 1
    With JavaScript arrays, it's really not practical to mix numeric and non-numeric keys. Arrays are all about the numerically indexed properties. Commented Mar 1, 2014 at 0:23

2 Answers 2

4

When an array has non-numeric keys, it's actually an object. Use for...in

for (key in levelinfoarray) {
    if (levelinfoarray.hasOwnProperty(key)) {
        console.log(key+') '+levelinfoarray[key][4]);
    }
}

P.S. don't use new Array, use array literals:

levelinfoarray["test"] = [16,20,4,5,"Test level"];
Sign up to request clarification or add additional context in comments.

3 Comments

This will work, but it's important to note that the order of property traversal is undefined.
An array is always an object. With strings as keys
This works great, it puts the test array at the end of the list, which is fine.
1
Object.keys(levelinfoarray) // => ["1", "2", "3", "test"]

To iterate:

Object.keys(levelinfoarray).forEach(function(key) {console.log(key)});

You'll have to polyfill Object.keys and Array.prototype.forEach, if you want to support older browsers.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.