1

Is there a cleaner/nicer/quicker way to do this?

taskList = new Array();
currentTask = new Object();
closedTask = new Object();
search = new Object();
taskList.push(currentTask); 
taskList.push(closedTask); 
taskList.push(search); 
1
  • 1
    taskList =[{},{},{}]; ? Commented Feb 19, 2014 at 10:13

5 Answers 5

4

Yeah, if you're not using currentTask, closedTask and search anywhere else you can do:

var taskList = [ {}, {}, {} ];

Otherwise:

var currentTask = {},
    closedTask = {},
    search = {};
var taskList = [ currentTask, closedTask, search];
Sign up to request clarification or add additional context in comments.

1 Comment

Please note that tasklist is not a property in the global scope.
2
var currentTask = {},
    closedTask = {},
    search = {},
    taskList = [currentTask, closedTask, search];

Comments

2

Both of these methods work, depending on what you are trying to accomplish.

var taskList = [{}, {}, {}] //Creates 3 Objects
OR
var taskList = [new Object(), new Object(), new Object()] //Object() can be replaced with any other object such as Array, String, etc

You can then just access the individual objects using:

taskList[x]; //Where x is the index of the object.

Comments

2

An even nerdier variant :

var currentTask,
    closedTask, 
    search,
    taskList = [currentTask={}, closedTask={}, search={}];

Joke aside, using the initializers syntax,
{} is basically equivalent to new Object and [] to new Array.

The braces syntax allows to create untyped objects (i.e. objects of the generic Object class), while the new operator allows to create class instances.

If you want to create an empty, untyped object, the result is equivalent.

Now consider this:

var Dog = function (value)
{
   this.bone= value;
}
Dog.prototype.bark = function () { console.log ("Woof!"); }

var Alf = new Dog (10); // Alf is a true able dog
var Rex = { bone:10 };  // Rex is just a generic object aping a dog

console.log (Alf.bone); // 10
console.log (Rex.bone); // 10
Alf.bark();             // Woof!
Rex.bark();             // generic objects don't bark !

4 Comments

Just to clarify, the "initializers syntax" is new Object(), new Array() or just the brackets/curly brackets?
"basically"? Nope. It is equivalent, even.
@Cerbrus Well nitpickers might object that a {} or [] initializer is not gramatically the same thing as the invokation of the new operator, but yes, for all practical purposes it is.
new object() and {} are both initializers with a different syntax :). See my edit
0

use:

taskList=[currentTask,closedTask,search];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.