2013-02-13 60 views
0

我在3位置插入一個值,插入值但以某種方式複製剩餘部分時,它不復制最後一個點。數組的大小沒有增加。任何人都可以告訴我如何在數組之間添加新元素。將數值插入到動作中的數組之間3.03

for(indexpoint=0;indexpoint<3;indexpoint++) 
{   
    temp.points[indexpoint].x = intpoints[indexpoint].x+this.x; 
    temp.points[indexpoint].y = intpoints[indexpoint].y+this.y; 
} 

temp.points[3].x = (intpoints[2].x+intpoints[3].x)/2+this.x; 
temp.points[3].y = (intpoints[2].y+intpoints[3].y)/2+this.y; 

for(indexpoint=3;indexpoint<intpoints.length;indexpoint++) 
{   
    temp.points[indexpoint+1].x = intpoints[indexpoint].x+this.x; 
    temp.points[indexpoint+1].y = intpoints[indexpoint].y+this.y;  
} 

回答

2

要在數組中插入新的元素,你可以使用的方法splice(),但首先,你必須創建要添加(它看起來像一個Point在你的代碼)對象:

const point:Point = new Point(); 
point.x = intpoints[2].x+intpoints[3].x)/2+this.x; 
point.y = intpoints[2].y+intpoints[3].y)/2+this.y; 

temp.points.splice(3, 0, point); 

你也可以這樣做:

temp.points.length = 0; 

for each (var point:Point in intpoints) { 
    temp.points.add(point.clone().add(this)); 
} 

const newPoint:Point = new Point(); 
newPoint.x = intpoints[2].x+intpoints[3].x)/2+this.x; 
newPoint.y = intpoints[2].y+intpoints[3].y)/2+this.y; 
temp.points.splice(3, 0, newPoint); 
+0

我這樣做了,現在發生了什麼,它會在數組末尾重複三次最後一個點。 – user1733735 2013-02-14 07:54:19

+0

什麼是'temp',你確定在第一個循環之前有'intpoints.length === temp.points.length'嗎?你爲什麼不開始填充你的值的空數組? – 2013-02-14 09:05:18

0

爲什麼不直接使用splice功能?

array.splice(positionToInsertIn, 0, newValue); 
+0

我這樣做了,現在發生了什麼,它會在數組的最後複製最後一個點三次 – user1733735 2013-02-14 07:51:40