So I've been racking my brain over why this doesn't work for hours now... What I'm trying to achieve is practically a "propagation" of rows through a 2D array. Basically, the first row of the array is set to random values, then that row is copied to the second row, and the first row is again filled with random values - repeating this until the row reaches the end of the array. Here's a visual example:
[0, 0, 0]
[1, 1, 1]
[2, 2, 2]
|
[3, 7, 2]
[0, 0, 0]
[1, 1, 1]
|
[5, 6, 8]
[3, 7, 2]
[0, 0, 0]
|
And so on...
I could do this quite easily in Python by creating a temp array that is equal to the original array before the new values are injected into the 0th row. Then, every row of the array is set to the current index-1 of the temp array, effectively shifting each row up by one.
However, in JavaScript, and specifically p5js, I can't seem to get it to work at all. When executing for loops in the draw() function, it's as if everything is either done asynchronously, or is not executed in the order I expect. Here's my code:
var arr = [], temp = [];
function setup() {
noLoop();
arr[0] = [0,0,0];
arr[1] = [1,1,1];
arr[2] = [2,2,2];
}
function draw(){
for(let k = 0; k < 3; k++){
temp[k] = arr[k];
}
console.table(arr);
for(let i = 0; i < 3; i++){
arr[0][i] = random(10)
}
console.table(arr);
arr[1] = temp[0];
arr[2] = temp[1];
console.table(arr);
}
I know I could use more for loops, however I used some individual indexes for now to make it more basic.
Note the positioning of the console.table(arr) statements - I'm under the impression that this code executes in the order that I write it, however each of the console statements produces the same table, as if all the code was run before writing anything to the console. Additionally, even though I'm setting temp to arr BEFORE arr is modified in any way, temp is being assigned the values of the arr AFTER the random values are set.
When looped continuously, this produces and array filled with the same random number, because it relies on temp storing the un-modified version of arr...
Maybe there's something obvious here I'm missing or I just don't know how JavaScript/p5.js works, but any help would be greatly appreciated!
Thanks :).