算法停止了,我不知道为什么

时间:2018-10-11 15:04:38

标签: javascript html function return

嘿!我正在尝试使用HTML,CSS和Javascript编码Pexeso。我有随机生成函数(不能多次使用数字-我用数组解决了这个问题)。然后我有另一个函数,该函数调用上述函数,并根据返回的img元素的id进行选择并设置图像源。一切看起来都很正确-IDE和Google Chrome浏览器不会返回任何错误,但是它仍然做不到正确的事情-它从不提供所有图像。

我正在放置代码,并在编译后显示其外观。

HTML

Me:- do you drink
Bot:- my brain does not require any beverages.
Me:- electricity
Bot:- electricity is nutrition for robots.
/*** If I post an answer it gives me the question next in the series ***\
Me:- electricity is nutrition for robots.
Bot:- are you experiencing an energy shortage?

/*** But this is what I expect if i give an answer it should not respond ***\
Me:- electricity is nutrition for robots.
Bot:- 'I am sorry, but I do not understand.'

JS

<!DOCTYPE html>
<html lang='cs'>
  <head>
    <title></title>
    <meta charset='utf-8'>
    <link href='style.css' rel='stylesheet' type='text/css'>
  </head>
  <body>
  <div class="container">
    <img class="pexeso" src="" id="1">
    <img class="pexeso" src="" id="2">
    <img class="pexeso" src="" id="3">
    <img class="pexeso" src="" id="4">
    <img class="pexeso" src="" id="5">
    <img class="pexeso" src="" id="6">
    <img class="pexeso" src="" id="7">
    <img class="pexeso" src="" id="8">
    <img class="pexeso" src="" id="9">
    <img class="pexeso" src="" id="10">
    <img class="pexeso" src="" id="11">
    <img class="pexeso" src="" id="12">
    <img class="pexeso" src="" id="13">
    <img class="pexeso" src="" id="14">
    <img class="pexeso" src="" id="15">
    <img class="pexeso" src="" id="16">       
  </div>
  <script src='app.js'></script>
  </body>
</html>

屏幕:https://prnt.sc/l4wr1q

1 个答案:

答案 0 :(得分:1)

问题:

当发现数字已经存在时,应中断循环并返回generateNumber的结果:

if (position[i] == number) {
    return generateNumber();
}

替代方式:

无论如何,可以通过删除递归调用并将整个内容包装在IIFE中进行封装来更好地实现函数generateNumber

var generateNumber = (function() {
  var numbers = [];

  return function() {
    var number;
    do {
      number = Math.floor(Math.random() * 16);
    } while(numbers.includes(number));
    numbers.push(number);
    return number;
  }
})();

最佳方式:

一种更好的方法是用数字(0到15)预填充数组,将它们混洗,然后每次调用该函数时,您只需popshift该数组中的一个数字即可:

var generateNumber = (function() {
  var numbers = [];

  for(var i = 0; i < 16; i++) numbers.push(i);

  for(var i = 0; i < 16; i++) {
    var randIndex = Math.floor(Math.random() * 16);
    var temp = numbers[i];
    numbers[i] = numbers[randIndex];
    numbers[randIndex] = temp;
  }

  return function() {
    return numbers.pop();
  }
})();