0

I don't understand why is array so strange when I add element by key. For example:

var test = new Array();
test['a'] = 'aaa';
test['b'] = 'bbb';

test.length == 0; // true. Why?

And when I run:

test.map(function(el){
   console.log(el);
});
// nothing print. Why?

When I add element with push method everything works OK. Thanks

7
  • 2
    Array !== Object Commented Jan 12, 2015 at 16:28
  • 1
    You're using array like it was an object. Commented Jan 12, 2015 at 16:28
  • JavaScript doesn't have associative arrays. Commented Jan 12, 2015 at 16:28
  • Arrays use numeric keys, for their Arrayness. Commented Jan 12, 2015 at 16:28
  • You're adding a property to the object, it doesn't change the length of an array. Commented Jan 12, 2015 at 16:28

1 Answer 1

2

Arrays in javascript are not associative, you can't set keys like that i.e.

var test = [];

test.push('aaa');
test.push('bbb');

// OR

test[0] = 'aaa';
test[1] = 'bbb';

test.length = 2
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.