在p5.js中使用拼接的问题

时间:2019-08-18 18:45:06

标签: javascript arrays p5.js splice

我正在使用p5.js编写程序。我需要在我的一个阵列上使用拼接。实际上,我有一个长度为10的初始数组(例如),其中包含对象,并且我希望其他对象包含除自身之外的所有其他对象。 而且我根本不理解为什么在调用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);
    }


  }
}

我希望10个数组的长度为9,而我的10个数组的长度为1

1 个答案:

答案 0 :(得分:3)

P5.js网站上的文档中的函数 Splice 用于“将一个值或值数组插入到现有数组中”。  因此,如果您要删除“每次迭代一个对象”,将无法使用。

如果要在JS中克隆数组(复制数组而不影响旧数组),则需要执行let NewArray = OldArray.slice(0);

我注意到在函数图形中您进行了temp=new nds(,但该变量在此范围中不存在。

最后一个注意事项是考虑使用let而不是var,我不想详细介绍,但是let可以避免很多问题。