2012-12-31 26 views
0

嘿所以我開始選擇Javascript,並且遇到了一些對象的問題。 我正在嘗試創建一個需要多個邊的形狀類。使用這些邊,它會創建更多特徵,以便存儲點的位置座標。 我現在所擁有的是一個正在考慮大小的類,我想使用for循環來創建存儲位置的「屬性」。僅僅爲了學習目的,我將它們設置爲0,以查看是否可以做到這一點。任何澄清對象將不勝感激。試圖通過for循環聲明一個對象的多個特徵

function Shape(size) { 
    this.size = size 
    for(var i=0; i<size; i++){ //tries to create the properties 
     //this[i].posX: 0; 
     //this[i].posY = 0; 
    } 
} 

理想情況下,我想這樣是訪問他們在這個類型的格式:

var triangle = new Shape(3); 
triangle[0].posX = 100; // So essentially I could set this to 100, the integer in the [] would represent a side. 
triangle[0].posY = 100; // etc ... for the rest of the sides 

的感謝!

回答

0

由於形狀可以具有可變數量的面,我會建議創建點的陣列作爲Shape類的屬性。

function Shape(size) { 
    this.size = size; 
    this.point = new Array();//stores an Array of Points 
    for(var i=0; i<size; i++){ 
     this.point[i] = new Point(0, 0); 
    } 
} 

function Point(x, y){ 
    this.posX = x || 0; 
    this.posY = y || 0; 
}; 

這樣,您就可以創建下面的代碼一個三角形:

// Creates a triangle with the points at (100, 100), (0, 0), and (0, 0) 
var triangle = new Shape(3); 
triangle.point[0].posX = 100; 
triangle.point[0].posY = 100; 

我希望這有助於。

+0

是的,我結束了思考數組,但我覺得有可能是一個更簡單的方法,然後創建一個新的對象數組。謝謝 – wzsun

0

我很難理解你的問題/問題是什麼。但在我看來,Javascript並不像C#或VB.NET或類似語言那樣真正支持'屬性'。您的解決方案使用兩種格式的方法:
1.設置值的方法。
2.返回值的方法。
所以,你的類應該有一些像這樣的4種方法:

setPosX(var posx) 
getPosX() 
setPosY(var posy) 
getPosY() 

然後你只需創建一個數組:

var triangles = new Array(); 

並通過給你的值循環:

function Shape(size) { 
     for(var i=0; i<size; i++){ //tries to create the properties 
      triangles[i].setPosX(0); // or any other value 
      triangles[i].setPosY(0); 
     } 
    } 

另請注意,此功能將在類結構之外。 希望這有助於;)

0

試試下面的代碼。那是你要的嗎?

function Shape(size) { 
    var arr = new Array(size); 

    for(var i=0; i <size; i++){ //tries to create the properties 
     arr[i] = { 
      posX: 0, 
      posY: 0 
     }; 
     //arr[i] = {}; 
     //arr[i].posX = 0; 
     //arr[i].posY = 0; 
    } 

    return arr; 
} 

現在你可以這樣做:

var triangle = new Shape(3); 
triangle[0].posX = 100; // So essentially I could set this to 100, the integer in the [] would represent a side. 
triangle[0].posY = 100; // etc ... for the rest of the sides 
相關問題