使用 p5.js 的接头时出现问题



我正在使用p5.js编写一个程序。我需要在我的一个数组上使用拼接。事实上,我有一个长度为 10 的初始数组(例如(,其中包含对象,我希望我的其他对象包含除自身之外的所有其他对象。 而且我完全不明白为什么我的代码在调用拼接时不起作用。

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

根据P5.js网站上的文档,函数Splice用于"将值或值数组插入现有数组"。 因此,如果要删除"每次迭代一个对象",这将不起作用。

如果你想在JS中克隆一个数组(复制一个数组而不影响旧数组(,你需要做let NewArray = OldArray.slice(0);

我注意到在函数图中你做了temp=new nds(但变量在这个范围内不存在。

最后一点,请考虑使用let而不是var,我不想详细介绍,但let会避免很多问题。

最新更新