6

I'm thinking maybe I missed something in JavaScript that I'm just picking up now.

I tried this code in Chrome console:

a = [];
a.name = "test";
JSON.stringify(a); 
// which returns value []
a = new Object();
a.name = "test";
JSON.stringify(a); 
// which returns value {"name":"test"}

What is the difference? I thought new Object() was a Microsoft JScript thing? What am I missing? Must have missed something in a spec somewhere. Thanks.

BuddyJoe
  • 69,735
  • 114
  • 291
  • 466
  • 2
    *"I thought new Object() was a Microsoft JScript thing?"* No, not at all. That's standard JavaScript (though it's verbose, just use `{}` instead -- which works fine in both JScript and other ECMAScript implementations). – T.J. Crowder May 16 '11 at 17:43

5 Answers5

20
a = new Object()

and

a = []

are not equivalent. But,

a = {}

and

a = new Object()

are.

gsamaras
  • 71,951
  • 46
  • 188
  • 305
Anurag
  • 140,337
  • 36
  • 221
  • 257
3

new Object() is equivalent to {} (except when it's not because of weird redefinition issues - but ignore that for now.) [] is equivalent to new Array(), to which you're then adding a .name property. JSON stringifies arrays in a special way that doesn't capture arbitrary property assignment to the array itself.

Dan Davies Brackett
  • 9,811
  • 2
  • 32
  • 54
1

For JSON data, Arrays are meant to have numeric indices, and objects have key/value pairs.

a = [];
a[ 0 ] = "test";

JSON.stringify(a); // returns value ["test"]
user113716
  • 318,772
  • 63
  • 451
  • 440
1

Yes you are using [] to define your object which is actually an array, but depending on the language you are coming from could be confusing because it is not an associative array.

Default objects are all maps of key->data and are instantiated with curly brackets {}

If you did

a = {};
a.name = "test";
JSON.stringify(a); 

It should work.

Quintin Robinson
  • 81,193
  • 14
  • 123
  • 132
  • *"... could be confusing because it is not an associative array"* Actually, it's more confusing than that, because it *is* an associative array, and non-numeric keys (property names) are perfectly valid in JavaScript, since [arrays aren't really arrays](http://blog.niftysnippets.org/2011/01/myth-of-arrays.html). But they'll get dropped if you convert the array to JSON, because JSON array notation doesn't allow non-numeric keys (for good reason, very few languages would support them). – T.J. Crowder May 16 '11 at 17:48
1

Setting the name property of an array does nothing to its serialized (JSON-stringified) form. It doesn't put an entry into the array. To do that, you need a.push('test').

Objects are standard parts of Javascript (see, for instance, the MDC docs). The normal way to create an object is with {}, but new Object() works too.

So...

var a = [];
a.push('test');
JSON.stringify(a); //"["test"]"

a = {};
a.name = 'test';
JSON.stringify(a); //"{"name":"test"}"
lonesomeday
  • 233,373
  • 50
  • 316
  • 318