Need help understanding why array in console.log is not displayed as expected

Hello!

the console.log in my p5 script is not showing what I expect and I do not understand, why.
Basically I want to create a random square matrix of zeroes and ones, but in the (rare) case the function returns only zeroes, I want to force at least one value to 1.
I wanted to confirm the behaviour of my code with console.log and check the array before and after the update.

function setup() {
  createCanvas(400, 400);
  let a = getRandomMatrix(3)
}

function getRandomMatrix(_size) {
  let _matrix = [];
  let _isValid = false;
  let _randVal;
  //fill the _matrix with random values 0 and 1:
  for (let i = 0; i < _size; i++) {
    for (let j = 0; j < _size; j++) {
      _index = _size * i + j;
      _randVal = int(random(0, 0)); // range is normally (0,2), but for testing I force all values to 0.
      _matrix[_index] = _randVal;
      //if any of the _matrix elements has a value > 0, then _matrix is valid:
      if (_randVal > 0) {
        _isValid = true;
      }
    }
  }
  //if all elements of _matrix are equal to 0
  //set one random element of _matrix to 1:

//HERE IS THE STRANGE BEHAVIOUR - I EXPECT THE CONSOLE.LOG TO BE DIFFERENT 
//BEFORE AND AFTER I FORCE ONE ELEMENT TO 1. BUT THE OUTPUT IS THE SAME
//SHOWING ONE ELEMENT TO BE 1 EVEN BEFORE THE IF-STATEMENT:
  console.log(_isValid, "1:  ", _matrix);
  if (!_isValid) {
    _matrix[floor(random(_matrix.length))] = 1;
  }
  console.log(_isValid, "2:  ", _matrix);
  return _matrix;
}

I hope my explanation makes any sense and you can tell me where my thinking/understanding is flawed.

many thanks,
Jochen

1 Like

thanks for the quick reply!
I take that this is a kind of strange p5 behavior that one just needs to know?
In the browser’s console the array-elements are indeed shown as expected.

Rather it’s browser JavaScript itself.

1 Like