JavaScript数组、Math

img


JavaScript数组、Math随机点名器任意创建一个包含五个以上的学生姓名的字符串数组,将数组作为参数代入genRandomName,将方法执行三次以上,随机抽选学生姓名,打印出来输出姓名要要求格式为次序加姓名


    <div id="app">
      <button id="btn">点名</button>
    </div>

    <script>
        let count = 0//执行次数
        let arr = ["张三","李四","王五","赵六","xxx"]
        let btn = document.getElementById("btn")

        btn.onclick = function(){
            count = 0
            console.log(genRandomName(arr))
        }
        function genRandomName(arr) {
            let str = "";
            let charIndex = Math.floor(Math.random() * arr.length);
            if (count < 3) {
                count++;
                genRandomName(arr);
            }
            return  charIndex + ":" + arr[charIndex];
        }

    </script>

img

产生随机数,在根据随机数匹配数组下标

img

Math.random() *5 然后 arr[Math.random() *5] 配合for循环