1

I am trying to track numbers with an array in the p5.js web editor, but am receiving some odd results which are not reproducible in a basic Javascript editor. In the below demo code, I expect the first print to show testArray containing 0, 1, 2, 3, and the second print to show "Hello", 1, 2, 3. However, the console produces "Hello", 1, 2, 3 from both print statements. I have tried varying the contents of the array, and a similar test with just an integer, and the array seems to be the problem. Why does the first print show side effects of an operation which should not have been performed yet?

Snippet:

function setup() {
  createCanvas(400, 400);
  testArray = [0, 1, 2, 3];
  print("Before: ", testArray);
  testArray[0] = "Hello";
  print("After: ", testArray);
}

function draw() {
  background(220);
}

Output:

Before:  (4) ["Hello", 1, 2, 3]
After:   (4) ["Hello", 1, 2, 3]
  • Many browser consoles log "live" versions of the object, and you only have one object, so you see its latest values. Try using `+` instead of `,` in the print to convert the array to a string when printing, or use `console.dir` or `JSON.stringify(arr, null, 2)` on larger structures. This behavior is probably not specific to p5. – ggorlen Oct 17 '22 at 13:12
  • Hi, check this answer: https://stackoverflow.com/questions/7389069/how-can-i-make-console-log-show-the-current-state-of-an-object – v.k. Oct 17 '22 at 13:12

0 Answers0