js—— 随机选择、模拟指定范围内点名

    let arr = ['张三','李四','王五','赵六']
        function arrayRandomFn(arr,start = 1,end){ 
            end = end?end:arr.length;
            start--;
            
            const index = start + Math.floor(Math.random()*(end-start));return arr[index]
        }
        console.log(arrayRandomFn(arr,1,2));
  1. 函数的形参表示的是从第几个到第几个随机抽取
  2. 函数内部的start和end表示的是开始结束的索引值
  3. 从指定位置开始结束的随机数,总结出了这样的规律
    1. Math.floor(Math.random()*(max-min+1); // 向下取整
      1. 例如:console.log(2+Math.floor(Math.random()*4));,打印的就是2-5之间的随机数
    2. Math.ceil(Math.random()*(max-min)); // 向上取整

7篇。

原文地址:https://www.cnblogs.com/xiaoyui/p/13744853.html