为了账号安全,请及时绑定邮箱和手机立即绑定

按下重置按钮后功能不起作用

按下重置按钮后功能不起作用

翻过高山走不出你 2021-04-15 10:15:40
“清除”按钮将数组清除为默认值,但是newGame函数此后拒绝运行。在调用Clear函数之前,newGame函数可以按预期正常工作。我相信新的游戏功能是元凶,但我不知道它的哪一部分可能会破坏它。第二次调用newGame之后,应该期待一个不同的数组,但是无论调用多少次,我最终都会得到一个空数组。let shuffledBoxes = [];let boxes = []let boxMax = 16;let boxCount = 0;const newGame = () => {  for (let i = boxes.length; i != boxMax; i++) {    if (boxes.length === boxMax) {      return null;    }    if (boxCount != Math.floor(boxMax * 0.4)) {      if (boxes.includes(2) === false) {        boxes.push(2);      }      boxes.push(1);      boxCount++;    } else {      boxes.push(0);    }  }};const randomBoxes = () => {  for (let i = boxes.length - 1; i >= 0; i--) {    math = Math.floor(Math.random() * boxMax);    shuffledBoxes.push(boxes[math]);    boxes.splice([math], 1);    boxMax--;  }};const boxesClear = () => {  for (let i = shuffledBoxes.length - 1; i > -1; i--) {    shuffledBoxes.pop();  }  for (let j = boxes.length - 1; j > -1; j--) {    boxes.pop();  }  boxCount = 0;};newGame();randomBoxes();boxesClear();//After this point, newGame does not like to run.newGame();randomBoxes();Logging boxes and shuffledBoxes show thatnewGame is working before boxClear is called.boxes =  []shuffledBoxes =  [ 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 2, 1, 0, 0, 0, 0 ]boxCount = 6boxes =  []shuffledBoxes =  []boxCount =  0
查看完整描述

1 回答

?
aluckdog

TA贡献1847条经验 获得超7个赞

你需要reset boxMax到16,因为它成为0在randomBoxes因


boxMax--;

Hide code snippet


let shuffledBoxes = [];

let boxes = []

let boxMax = 16;

let boxCount = 0;


const newGame = () => {

  for (let i = boxes.length; i != boxMax; i++) {

    if (boxes.length === boxMax) {

      return null;

    }

    if (boxCount != Math.floor(boxMax * 0.4)) {

      if (boxes.includes(2) === false) {

        boxes.push(2);

      }

      boxes.push(1);

      boxCount++;

    } else {

      boxes.push(0);

    }

  }

};


const randomBoxes = () => {

  for (let i = boxes.length - 1; i >= 0; i--) {

    math = Math.floor(Math.random() * boxMax);

    shuffledBoxes.push(boxes[math]);

    boxes.splice([math], 1);

    boxMax--;

  }

};


const boxesClear = () => {

  for (let i = shuffledBoxes.length - 1; i > -1; i--) {

    shuffledBoxes.pop();

  }

  for (let j = boxes.length - 1; j > -1; j--) {

    boxes.pop();

  }

  boxCount = 0;

  boxMax = 16

};


newGame();

randomBoxes();




boxesClear();

//After this point, newGame does not like to run.



newGame();

randomBoxes();



console.log(shuffledBoxes);

console.log(boxes);

您也可以缩短boxesClear功能


const boxesClear = () => {

  shuffleBoxes = [];

  boxes = [];

  boxCount = 0;

};

您也可以使用一个衬管。


const boxesClear = () => shuffleBoxes.length = boxes.length = boxCount = 0


查看完整回答
反对 回复 2021-04-22
  • 1 回答
  • 0 关注
  • 138 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信