Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
253 views
in Technique[技术] by (71.8m points)

arrays - Javascript splice function not working correctly

Relatively new programmer here. I have a fully functioning Tetris game written in Javascript. I am having problems with the final function - where splice is not working as expected in removing a row filled with color. Im sure there might be something wrong with the way I have looped through the arrays but I cannot work it out and was wandering if anyone could offer some advice. Here is my current function that is called everytime a shape collides with another:

  for(let y = arena.length-1; y < 0; y--){
    for(let x = 0; x < arena[y].length; x++){
      if (arena[y][x] === 0) {
        continue;
      } 
    }
    const row = arena.splice(y,1)[0].fill(0);
    arena.unshift(row);
    y++;
  };
}
question from:https://stackoverflow.com/questions/65851753/javascript-splice-function-not-working-correctly

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Fixed it up for ya. You had a couple of concepts wrong:

function arenaSweep() {
  for(let y = arena.length-1; y >= 0; y--){
    const row = arena[y];
    let filled = true;
    
    for(let x = 0; x < row.length; x++){
      if (row[x] === 0) {
        filled = false;
        break;
      } 
    }
    
    if (filled) {
      arena.splice(y,1);
      row.fill(0);
      arena.unshift(row);
      y++;
    }
  };
}

The conditional in your for loop had the wrong direction (y < 0 should be y >= 0) for reverse loops.

Next you assumed continue would break out of the inner loop so you could start checking next row; however, it's break that stops the current loop. Continue just made you move to the next iteration of the nested loop.

I also optimized a little by reducing array calls.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...