JSON.stringify () and JavaScript objects

I think maybe I missed something in JavaScript that I am just compiling now.

I tried this code in the 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 the new object () was the subject of Microsoft JScript? What am I missing? Must have missed something in the spec. Thank you

+6
source share
5 answers
 a = new Object() 

and

 a = [] 

not equivalent. But,

 a = {} 

and

 a = new Object() 

there is.

+20
source

new Object() equivalent to {} (unless it is due to strange redefinition problems, but ignores it for now.) [] equivalent to new Array() to which you add the .name property. JSON builds arrays in a special way that does not capture the arbitrary assignment of properties to the array itself.

+3
source

For JSON data, arrays must have numeric indices, and objects have key / value pairs.

 a = []; a[ 0 ] = "test"; JSON.stringify(a); // returns value ["test"] 
+1
source

Yes, you use [] to define your object, which is actually an array, but depending on the language you came from, it can be confusing because it is not an associative array.

The default objects are all key-> data cards and are created with curly braces {}

If you did

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

It should work.

+1
source

Setting the name property of an array does nothing for its serialized (JSON string) form. It does not put the record into an array. For this you need a.push('test') .

Objects are standard parts of Javascript (see, for example, MDC docs ). The usual way to create an object is {} , but new Object() also works.

So...

 var a = []; a.push('test'); JSON.stringify(a); //"["test"]" a = {}; a.name = 'test'; JSON.stringify(a); //"{"name":"test"}" 
+1
source

Source: https://habr.com/ru/post/888247/


All Articles