Strange access to data class

Hi,
I’ve noticed a strange behavior through the setup() et draw() method in a classical p5.js sketch.

here is a brief example :

file classTest.js :

class classTest{
constructor(c1, c2, c3){
this.groupe = [c1, c2, c3];
}

permute(){
this.groupe.unshift(this.groupe.pop());
}

}

file sketch.js :

let myTest = new classTest(1,2,3);
function setup() {
createCanvas(400, 400, WEBGL);

console.log(myTest.groupe);
myTest.permute();
console.log(myTest.groupe);
}

the console output should be :

[1,2,3]
[3,1,2]

but in my case it is :

[3,1,2]
[3,1,2]

the first output is already altered by the method permute() but it shouldn’t be and I don’t know why.
Notice that the right output occurs when using javascript not with p5.js i.e :

<meta charset="utf-8" />
<script>

class classTest{
constructor(c1, c2, c3){
this.groupe = [c1, c2, c3];
}

permute(){
this.groupe.unshift(this.groupe.pop());
}

}

let myTest = new classTest(1,2,3);

console.log(myTest.groupe);
myTest.permute();
console.log(myTest.groupe);

Instead

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

    console.log(myTest.groupe);

}

What happens now???

I would like to have the both output in the console, before the permute() method and after.

let myTest = new classTest(1,2,3);
function setup() {
createCanvas(400, 400, WEBGL);

console.log(myTest.groupe); // should print [1,2,3] -> values get from constructor class. it doesn't
myTest.permute();
console.log(myTest.groupe); // should print [3,1,2] and it does
}

Understood

Just as a test

What does my example give you in the console?

You can just comment the lines out.

Right, I didn’t mentionned that

alone, the first outup work well and reply [1,2,3] but the same line when followed by the method call and an second output doesn’t work as expected.

By the way, at the end of the code, the values are correct but I don’t understand the behavior and it might be usefful to when debbuging.

Both outputs in my browser got the expected values: [1, 2, 3] & [3, 1, 2].

But b/c you’re printing an array, if a browser by chance delays the actual printing to the console, it’s possible that you’ll see the array’s most current values for all outputs.

As a workaround you can extract the arrays values when printing it using the spread ... syntax:
console.log(...myTest.groupe);

1 Like

It appears that false output occurs only in the p5js editor. If I run the same code by simply editing files and opening the index.html directly with my browser it work perfecly well !

so, is this a fail in the p5js editor ? and by the way the problem seems to be fixed ?