Welcome to WebmasterWorld Guest from 107.20.108.136

Forum Moderators: open

Message Too Old, No Replies

Single Line Associative Array Object

Can it be done in a single line?

     
7:40 am on Oct 6, 2011 (gmt 0)

Senior Member from US 

WebmasterWorld Senior Member jab_creations is a WebmasterWorld Top Contributor of All Time 10+ Year Member

joined:Aug 26, 2004
posts: 3148
votes: 12


A numerical array can be done in JavaScript in a single line...

var a = new Array('a','b','c');


However I'm curious if there is a way to define an associative object in a single line using the new Object syntax instead of the following shortcut...

var a = {'a':'1','b':'2','c':'3'};


I already tried the following which does not work (using curly, curved or solid brackets)...

var a = new Object{'a':'1','b':'2','c':'3'};


Also using a semi-colon to separate items on the same line doesn't count. Thoughts please?

- John
9:47 am on Oct 6, 2011 (gmt 0)

Senior Member

WebmasterWorld Senior Member penders is a WebmasterWorld Top Contributor of All Time 5+ Year Member Top Contributors Of The Month

joined:July 3, 2006
posts: 3123
votes: 0


By calling:
var a = new Object(something);


You are passing something to the Objects underlying constructor method. For your own objects this is whatever you define. In the case of the base Object, this results in the creation of an object of whatever data type you pass to it...

var myNumber = new Object(123); // number Object 
var myString = new Object('Hello'); // string Object
var myObject = new Object({'a':'1','b':'2','c':'3'}); // object Object


So, I think, in order to do what you are trying to achieve you would need to pass an object literal to the constructor (as in the last example). But I don't think there is any point in this (and jslint advises against this), since you might as well just define the object literal.
 

Join The Conversation

Moderators and Top Contributors

Hot Threads This Week

Featured Threads

Free SEO Tools

Hire Expert Members