2014-09-20 50 views
0

我有一個對象數組,我試圖遍歷數組中的每個對象。我需要在每個對象上調用一個方法。我應該如何去做這件事?迭代js中的數組屬性方法

function basicBox(x,y,width,height,color) { 
    this.color = color; 
    this.x = x; 
    this.y = y; 
    this.width = width; 
    this.height = height; 
    this.draw = function() { 
     g.drawStyle = this.color; 
     g.drawRect(this.x,this.y,this.width,this.height); 
    } 
} 

var boxes = [b1,b2,b3]; 

function run() { 
    for (var i = 0; i < boxes.length; ++i) { 
     boxes[i].update(); 
    } 
} 
+0

請參閱:http://stackoverflow.com/questions/684672/loop-through-javascript-object – 2014-09-20 04:02:23

+1

'update'或'draw'?什麼是'g'? – elclanrs 2014-09-20 04:04:21

回答

0

它認爲Array.map()Array.reduce()當然Array.forEach()可以幫助你和你所要求的東西。使用forwhile循環絕對足以迭代數組,但值得嘗試更多功能的方法,因爲它可以防止重寫循環,並讓您專注於任務,每個元素都應該完成。

如果您想遍歷Object的屬性,則可以使用for in循環,但也有Object.keys()什麼返回給定對象的所有屬性。