0

I am inserting a value on 3 position the value is being inserted but somehow while copying the rest part it does not copy the last point. The size of an array is not increasing. Can anyone tell me how to add new elements in an array in between.

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 Answers 2

2

To insert new elements in an array, you can use the method splice(), but first, you have to create the object that you want to add (it looks like a Point in your code):

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);

You could also do this:

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);
Sign up to request clarification or add additional context in comments.

2 Comments

I did this,now what happens it duplicates the last point three times at the end of the array.
What is temp, and are you sure that intpoints.length === temp.points.length before the first loop? Why don't you start with an empty array that you fill with your values?
0

Why not just use the splice function?

array.splice( positionToInsertIn, 0, newValue );

1 Comment

I did this,now what happens it duplicates the last point three times at the end of the array

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.