2016-07-31 101 views
2

上下文:我正在構建一個基於代理的模型房地產市場模擬。我有一個具有屬性和方法,到目前爲止,我已經創造了他們這樣的家用物品:新對象實例,生成器,數組,名稱生成

var houseHoldArray = []; 

var Household = function(name, house) { 
    this.name = name; 
    this.house = house.address; 
    this.x = house.x; 
    this.y = house.y; 
    this.isHomeOwner = true; 
    this.isSelling = false; 

}; 

Household.prototype.draw = function() { 
ellipse(this.x, this.y, 10, 10); 
}; 

Household.prototype.determinMove = function() { 
    if(random(0, 100) <= 75){ 
     this.isSelling = true; 
    } 
}; 

var household1 = new Household("Smith", house1); 
var household2 = new Household("Black", house2); 
var household3 = new Household("Johnson", house3); 
var household4 = new Household("Williams", house4); 
var household5 = new Household("Jones", house5); 

houseHoldArray.push(household1, household2, household3, household4, household5); 

household1.draw(); 
household2.draw(); 
household3.draw(); 
household4.draw(); 
household5.draw(); 

我現在要創建一個函數,觸發在點擊一個按鈕,會自動創建一定數量的新家庭實例並將它們存儲在數組中,因爲稍後需要使用for循環遍歷它們,並根據它們的isSelling和isHomeowner屬性的狀態執行某些操作。

問題:我該如何創建一個函數,點擊一個按鈕後,會生成一定數量的新對象實例並將它們推送到houseHoldArray

您可能會發現一個更有效的方式做到這一點,但在最後,我想有一個包含個人家庭的信息,讓我跑像這樣的數組:

for (var i = 0; i < houseHoldArray.length; i++) { 
    if houseHoldArray[i].isSelling { 
     //do something 
    } 
    houseHoldArray[i].determinMove() 
} 

回答

0

而不是使用「 houseHold1,houseHold2「,我們已經將它們用作數組。與房屋一樣。就像這樣:

<button onclick='addHouseHolds(5, ["Smith", "Black", "Johnson","Williams","Jones"], [0,1,2,3,4])'>Click me</button> 

var houseHoldArray = []; 
var houses = [new House(), new House(), new House(), new House(), new House()]; 
function addHouseHolds(number, names, houseIndexes){ 
    for(var i = 0; i < number; i++){ 
     household = new Household(names[i],houses[ houseIndexes[i] ]); 
     houseHoldArray.push(household); 
    } 
} 
在HTML