2013-02-13 57 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