0

I'm using P5.js to make a connect 4 game that I later want to use to make some training data for a ML project. I'm just currently working on making some logic. In a separate file, (separate just so I can test ideas) I have it so you hit a number 1-7 as a row number, and then it will color in your spot on the board. I'm using the logic system to know how far down the colored block needs to go. I have some arrays corresponding to the columns, and for testing purposes, I have 4 columns of 3 down. A 1 represents somewhere a piece is, and a 0 is an open space. When in a column, I use a for loop to iterate through, and if i is a 1, and i-1 is a 0, change i-1 to be a 1. This effectively simulates the gravity of dropping a piece down. The problem is, when I run console.log, both before and after my logic, it gives my the same result, but it's the post logic result. I don't know why it won't log the correct pre-logic array. My code is:

row = [2];
nums = [
  [0,0,0],
  [0,0,1],
  [0,1,1],
  [1,1,1]
]

console.log(nums[row])

//console.log(nums[row].length - 1)
for (i = 0; i<= ((nums[row].length) - 1); i++) {
  //console.log(nums[row])
  // console.log(i)
  if ((nums[row][i]) == 1 && nums[row][i-1] == 0) {
    nums[row][i-1] = 1
  }

  /*console.log(nums[row][i])*/
}

console.log(nums[row])

Before I run the logic, it shoud log [0,1,1] and after it should be [1,1,1]. Instead, any time I run it on a row that gets changed, it logs the output twice. I don't know why it isn't logging the array before it gets changed first. Any help would be great!

joelanbanks3
  • 318
  • 3
  • 14
  • Check the answers to [this question](https://stackoverflow.com/questions/11284663/console-log-shows-the-changed-value-of-a-variable-before-the-value-actually-ch) – Julian Dec 03 '19 at 01:42

1 Answers1

0

Yes, this can be annoying, and you should read certainly read the linked comment. But for a quick/dirty solution, you can use a function like the following:

function console_log(o)
  console.log(JSON.parse(JSON.stringify(o)))
}

then call console_log(nums[row]) instead of console.log(nums[row])

rednoyz
  • 1,318
  • 10
  • 24