Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
70
rated 0 times [  76] [ 6]  / answers: 1 / hits: 16107  / 11 Years ago, tue, june 4, 2013, 12:00:00

Well I have always used



var j= {};
j['field'] = value;


Apparently below works too



var j= [];
j['field'] = value;


Any difference?



Edit: Sorry I guess I used the wrong word json here instead of object. My bad. But my questions till stands. Most people are explaining the difference between an array and object to me which I am familiar with.



I always do var x = []; x.push('blah') etc.



I also do var x = {}; x.Name = 'Michael'; x.Age = 21 etc.



What I was surprised to see and what prompted me to ask this is I saw code that goes like
var x = [];
x.name = 'Michael';



This is something I wasn't used to and hence posted the question.



Thanks for all the answers. I have marked accepted answer which addressed my question the best


More From » json

 Answers
12

Your objects aren't JSON, they're (empty) object and array literals. JSON is the serialized form you get by passing such a value of JSON.stringify.



The latter won't work if you do try to convert it to JSON, even though it's legal JavaScript:



var json = [];             // ok, it's an array
json[field] = value; // still OK - arrays can have properties too
JSON.stringify(json);
> []


i.e. you just get an empty array, because when you try to serialize an array you only get out the numerically indexed properties from 0 to myArray.length - 1, and not named properties.


[#77823] Monday, June 3, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
rhett

Total Points: 671
Total Questions: 100
Total Answers: 102

Location: Hong Kong
Member since Tue, Oct 19, 2021
3 Years ago
;