homepage Welcome to WebmasterWorld Guest from 54.198.157.6
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Become a Pro Member
Home / Forums Index / Code, Content, and Presentation / JavaScript and AJAX
Forum Library, Charter, Moderator: open

JavaScript and AJAX Forum

    
Single Line Associative Array Object
Can it be done in a single line?
JAB Creations




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

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

 

penders




msg:4371459
 9:47 am on Oct 6, 2011 (gmt 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.

Global Options:
 top home search open messages active posts  
 

Home / Forums Index / Code, Content, and Presentation / JavaScript and AJAX
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved