0

I have an array which holds sub-arrays, the main array has custom keys; used as an identifier. The problem is I can't access the array with these keys set e.g:

array.length - returns 0 when clearly it has values

In console:

[evt1: Array[0], evt2: Array[0]]
evt1: Array[0]
evt2: Array[0]

When changed back to a standard index (0,1,2), the array can be accessed - and performs as normal. Why is this happening?

Thanks

2
  • 2
    Arrays dont have keys, they have indexes. Objects have keys, and each key of an object could contain an array. Commented Apr 23, 2014 at 20:11
  • 1
    @tymeJV To be picky, the arrays are objects and they get a key/property for each index e.g. [4,5,6].hasOwnProperty('1') //true Commented Apr 23, 2014 at 20:17

2 Answers 2

1

As stated in comments, you are not using an array, you are using an object. Use Object.keys(your_object).length to get length, and to travel through indexes:

for(var index in your_object){
    console.log(index,your_object[index]);
} 

You can also do:

var indexes=Object.keys(your_object);
for(var i=0;i<indexes.length;i++){
    console.log(indexes[i], your_object[indexes[i]]);
}
Sign up to request clarification or add additional context in comments.

4 Comments

@Martin The for..in loop is used to iterate object properties in Javascript
I know that. But I've never seen this way of iterating over objects
@Martin Then what have you seen o.O
Ok I've seen the for ... in loops before (obviously) but I've never seen Object.keys(your_object).length to be used in a regular for loop. The answer was edited since my first comment
1

Arrays (like many other things in javascript) can have properties just like objects, however, array properties do not count toward the length of the array. What you should use is an object as the outer structure that contains your keys->arrays.

{evt1: Array[0], evt2: Array[0]}

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.