js 获取指定范围随机数

133 阅读1分钟

一、随机获取1-10范围内数字

let random = Math.floor((Math.random() * 10) + 1)

console.log(random)  // 6

二、随机获取指定数组内的值

let arr = ['a', 'b', 'c']
let index = Math.floor(Math.random() * arr.length)

console.log(arr[index])  // c

三、随机获取指定范围内的值

function rand(m, n)  {
    return Math.ceil(Math.random() * (n-m+1) + m-1)
}

rand(60, 100)  // 随机输出60-100之间的值