简体   繁体   中英

.push doesn't seem to be adding to my array

I have called the .push function, but nothing is being added to my array. Here is my code:

function setup() {
  createCanvas(400, 400);
}
let digits = [];
function binaryConverter(num){
  this.num = num;
    for(let i = 0; this.num === 0; i++){
    digits.push(this.num % 2);
    this.num = floor(this.num/=2);
  }
}
function draw() {
  background(220);
  binaryConverter(13);
  print(digits);
}

I expected the program to output the digits, but it outputs empty arrays.

The second statement in the for loop defines the condition which has to be fulfilled for executing the code block of the loop. The code block of the loop is executed as long as the condition is fullfilled

The initial value of this.num is num (which is 13 in your case). So the condition this.num === 0 is never fulfilled and the statements in the code block of the loop are never executed.

Change the condition statement in the for loop:

for(let i = 0; this.num === 0; i++)
for(let i = 0; this.num != 0; i++)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM