Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Array Object vs Array Like Objects - Clarification

I was trying to stringify an array-like object that was declared as an array object and found that JSON.stringify wasn't processing correctly array-like object when it is defined as an array object.

See below for more clarity, --> jsFiddle

var simpleArray = []; //note that it is defined as Array Object 

alert(typeof simpleArray); // returns object -> Array Object

simpleArray ['test1'] = 'test 1';
simpleArray ['test2'] = 'test 2';

alert(JSON.stringify(simpleArray)); //returns [] 

It worked fine and returned me {"test1":"test 1","test2":"test 2"} when I changed

var simpleArray = []; to var simpleArray = {};.

Can someone shed some light or some reference where I can read more?

Edit:

Question: When typeof simpleArray = [] and simpleArray = {} returned object, why JSON.stringify wasn't able to return {"test1":"test 1","test2":"test 2"} in both cases?

like image 223
Selvakumar Arumugam Avatar asked Feb 07 '12 21:02

Selvakumar Arumugam


1 Answers

The difference is the indexes. When you use an array [] the indexes can only be positive integers.

So the following is wrong:

var array = [ ];
array['test1'] = 'test 1';
array['test2'] = 'test 2';

because test1 and test2 are not integers. In order to fix it you need to use integer based indexes:

var array = [ ];
array[0] = 'test 1';
array[1] = 'test 2';

or if you declare a javascript object then the properties can be any strings:

var array = { };
array['test1'] = 'test 1';
array['test2'] = 'test 2';

which is equivalent to:

var array = { };
array.test1 = 'test 1';
array.test2 = 'test 2';
like image 172
Darin Dimitrov Avatar answered Sep 18 '22 11:09

Darin Dimitrov