Math.random复制数字JavaScript

时间:2019-03-20 10:26:15

标签: javascript jquery

我想在两个方框中随机分配一个班级。

但是即使使用 [HttpPost] public async Task<IActionResult> Edit(EditPropertyViewModel model) { if (ModelState.IsValid) { /* Update property here and return */ } return View(model); } ,Math.random也会复制数字。

如果刷新,将会看到这些框正在更改类,但有时它们都具有相同的类,这应该发生。

indexOf(randomIndex) === -1)
  var grid = document.getElementById("grid-box");

  for (var i = 0; i <= 1; i++) {
    var square = document.createElement("div");
    square.className = 'square';
    square.id = 'square' + i;
    grid.appendChild(square);
  }


  var weaponTwo = [];

  while (weaponTwo.length < 1) {
    var randomIndex = parseInt(2 * Math.random());


    if (weaponTwo.indexOf(randomIndex) === -1) {
      weaponTwo.push(randomIndex);


      var drawWtwo = document.getElementById('square' + randomIndex);
      $(drawWtwo).addClass("w2")

    }
  };

  var weapon3 = [];

  while (weapon3.length < 1) {
    var randomIndex = parseInt(2 * Math.random());


    if (weapon3.indexOf(randomIndex) === -1) {
      weapon3.push(randomIndex);


      var draw3 = document.getElementById('square' + randomIndex);
      $(draw3).addClass("w3")

    }
  };
  #grid-box {
    width: 420px;
    height: 220px;
  }
  #grid-box>div.square {
    font-size: 1rem;
    vertical-align: top;
    display: inline-block;
    width: 10%;
    height: 10%;
    box-sizing: border-box;
    border: 1px solid #000;
  }
  .w2 {
    background-color: red;
  }

  .w3 {
    background-color: blue;
  }

1 个答案:

答案 0 :(得分:1)

您正在使用两个不同的阵列来存储武器。使用相同的数组,以使数字不再重复。

  var grid = document.getElementById("grid-box");

  for (var i = 0; i <= 1; i++) {
    var square = document.createElement("div");
    square.className = 'square';
    square.id = 'square' + i;
    grid.appendChild(square);
  }


  var weaponTwo = [];

  while (weaponTwo.length < 1) {
    var randomIndex = parseInt(2 * Math.random());


    if (weaponTwo.indexOf(randomIndex) === -1) {
      weaponTwo.push(randomIndex);


      var drawWtwo = document.getElementById('square' + randomIndex);
      $(drawWtwo).addClass("w2")

    }
  };

  while (weaponTwo.length < 2) {
    var randomIndex = parseInt(2 * Math.random());


    if (weaponTwo.indexOf(randomIndex) === -1) {
      weaponTwo.push(randomIndex);


      var draw3 = document.getElementById('square' + randomIndex);
      $(draw3).addClass("w3")

    }
  };
  #grid-box {
    width: 420px;
    height: 220px;
  }
  #grid-box>div.square {
    font-size: 1rem;
    vertical-align: top;
    display: inline-block;
    width: 10%;
    height: 10%;
    box-sizing: border-box;
    border: 1px solid #000;
  }
  .w2 {
    background-color: red;
  }

  .w3 {
    background-color: blue;
  }
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>

  <div id="grid-box"></div>

更好的方法:您可以创建一个类数组,然后使用this alogrithm对其进行混洗。然后,您可以从数组中弹出并逐一添加到类中。