更快速地实例化和填充对象数组

时间:2014-02-19 10:11:39

标签: javascript

有更干净/更好/更快的方法吗?

taskList = new Array();
currentTask = new Object();
closedTask = new Object();
search = new Object();
taskList.push(currentTask); 
taskList.push(closedTask); 
taskList.push(search); 

5 个答案:

答案 0 :(得分:4)

是的,如果你没有使用currentTask,closedTask并在其他任何地方进行搜索:

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

否则:

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

答案 1 :(得分:2)

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

答案 2 :(得分:2)

这两种方法都有效,具体取决于您要完成的任务。

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

然后您可以使用以下方式访问各个对象:

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

答案 3 :(得分:2)

一个更加神秘的变体:

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

暂且不说,使用初始化器语法,
{}基本上相当于new Object[]new Array

大括号语法允许创建无类型对象(即通用Object类的对象),而new运算符允许创建类实例。

如果要创建一个空的无类型对象,结果是等效的。

现在考虑一下:

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 :(得分:0)

使用:

taskList=[currentTask,closedTask,search];