Search code examples
javascriptarraysp5.jssplice

Issue using splice with p5.js


I am writing a programme using p5.js. I need to use splice on one of my arrays. Indeed I have an initial array (for example) with a length of 10 which contain objects and I want my other objects to contain every other object except their selves. And I don't understand at all why does my code doesn't work when I'm calling splice.

var test;

function setup() {
  createCanvas(400, 400);

  test=new graphe(10);
  test.randomconnect();

  for(i=0;i<test.tabNds.length;i++){

    var temp=test.tabNds; //initial array
    test.tabNds[i].initiate(temp);
  } 
  for(var i=test.tabNds.length;i>=0;i--)
  {
    var temp=test.tabNds; //copy of my initial array, and i want to remove JUST one object per iteration
    temp.splice(1,i);
  }
}

function draw() {
  background(220);

  for (i=0;i<test.tabNds.length;i++){

    test.tabNds[i].show();
  }
}


function _arc(x1,y1,x2,y2){

  this.xstart=x1;
  this.ystart=y1;
  this.xend=x2;
  this.yend=y2;
  this.weight=dist(this.xstart,this.ystart,this.xend,this.yend);

  this.show=function(){
    strokeWeight(1);
    color(255);
  line(this.xstart,this.ystart,this.xend,this.yend);
  }
}

function nds(x_,y_,number_){
  this.x=x_;
  this.y=y_;
  this.number=number_;
  this.tabOthers=[];

  this.initiate=function(others)
  {
    this.tabOthers=others;
  }  


  this.show=function(){

  strokeWeight(20);
  point(this.x,this.y)

  }
}


function graphe(nbNds_)
{
  this.nbNds=nbNds_;
  this.tabNds=[];
  console.log(this.nbNds);
  this.randomconnect=function(){

    for(var i=0;i<this.nbNds;i++){

    temp=new nds(random(0,height),random(0,height),i);//creation des points
    this.tabNds.push(temp);
    }


  }
}

I expect 10 arrays with a length of 9 whereas I have 10 array length 1


Solution

  • The function Splice according to the documentation in the P5.js website is used to "Inserts a value or an array of values into an existing array." so if you want to remove "one object per iteration" this will not work.

    If you want to clone an array (copy an array without impacting the old one) in JS you need to do let NewArray = OldArray.slice(0);

    I notice that in function graphe you do temp=new nds( but the variable doesn't exist in this scope.

    One last note consider using let instead of var, I don't want to enter into details but let will avoid you lots of problems.