是否有更乾淨/更好/更快的方法來做到這一點?更快的方式來實例化和填充對象陣列
taskList = new Array();
currentTask = new Object();
closedTask = new Object();
search = new Object();
taskList.push(currentTask);
taskList.push(closedTask);
taskList.push(search);
是否有更乾淨/更好/更快的方法來做到這一點?更快的方式來實例化和填充對象陣列
taskList = new Array();
currentTask = new Object();
closedTask = new Object();
search = new Object();
taskList.push(currentTask);
taskList.push(closedTask);
taskList.push(search);
是啊,如果你不使用currentTask,closedTask和搜索其他地方,你可以這樣做:
var taskList = [ {}, {}, {} ];
否則:
var currentTask = {},
closedTask = {},
search = {};
var taskList = [ currentTask, closedTask, search];
請注意,'tasklist'不是全局範圍內的屬性。 – Cerbrus
注意。謝謝! – spassvogel
使用:
taskList=[currentTask,closedTask,search];
var currentTask = {},
closedTask = {},
search = {},
taskList = [currentTask, closedTask, search];
這兩種方法都有效,具體取決於您要完成的工作。
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.
更像是這樣:D +1 – Cerbrus
一個甚至nerdier變種:
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 !
TASKLIST = [{},{},{}]; ? – Alberto