猿问

从数组中删除唯一的随机项目,然后重新填充以重新启动该过程?

var myArray = ['A','B','C'];

document.getElementById("button").onclick = function() {

    if (myArray.length > 0) {

      var a = Math.floor(Math.random() * myArray.length);

      var b = myArray.splice(a, 1);

      document.getElementById("showRand").innerHTML = b[0];

    } else { 

      //restart

    }

}

<button id="button">click</button>

<div id="showRand"></div>

Onclick时,它随机清空myArray,如何重新填充数组,然后在myArray为空时重复该过程?

感谢您的帮助..


慕的地10843
浏览 54回答 1
1回答

心有法竹

var myArray = ['A','B','C'];document.getElementById("button").onclick = function() {&nbsp; &nbsp; if (myArray.length == 0) {&nbsp; &nbsp; &nbsp; myArray = ['A','B','C'];&nbsp; &nbsp; }&nbsp; &nbsp; var a = Math.floor(Math.random() * myArray.length);&nbsp; &nbsp; var b = myArray.splice(a, 1);&nbsp; &nbsp; document.getElementById("showRand").innerHTML = b[0];}<button id="button">click</button><div id="showRand"></div>
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答