Math對(duì)象方法的使用方式: Math.方法名(實(shí)參...)
1. 隨機(jī)小數(shù): 0-1之間, random()
2. 取整方式
? ? ? ? 2.1 ceil(): 向上取整, Math.ceil(參數(shù))? ? : 天花板數(shù)
? ? ? ? 2.2 floor(): 向下取整, Math.floor(參數(shù))? : 地板數(shù)
? ? ? ? 2.3 round(): 四舍五入, Math.round(參數(shù))
3. 求最大值和最小值
? ? ? ? 3.1 max(): 最大值, 不限定參數(shù)
? ? ? ? 3.2 min(): 最小值, 不限定參數(shù)
?4. 求冪: x 的 y 次方: Math.pow(底數(shù)x,指數(shù)y)
如何生成任意范圍隨機(jī)數(shù)
1、 如何生成0-10的隨機(jī)數(shù)呢甲献?
Math.floor(Math.random() * (10 + 1))
2宰缤、如何生成5-10的隨機(jī)數(shù)?
Math.floor(Math.random() * (5 + 1)) + 5
3晃洒、如何生成N-M之間的隨機(jī)數(shù)
Math.floor(Math.random() * (M - N + 1)) + N
求:0-N之間隨機(jī)正數(shù)
1. 隨機(jī)0-1之間的小數(shù): Math.random()
2. 放大指定倍數(shù): * N
3. 取整: 如果是兩端都有 Math.round(), 如果不包含小: Math.ceil()? 如果只要小: Math.floor()
其中: Math.ceil()是不大安全的: 可能隨機(jī)到0( 一般會(huì)忽略概率)
隨機(jī)點(diǎn)名案例
需求:請(qǐng)把 [‘趙云’, ‘黃忠’, ‘關(guān)羽’, ‘張飛’, ‘馬超’, ‘劉備’, ‘曹操’] 隨機(jī)顯示一個(gè)名字到頁(yè)面中
分析:
①:利用隨機(jī)函數(shù)隨機(jī)生成一個(gè)數(shù)字作為索引號(hào)
②: 數(shù)組[隨機(jī)數(shù)] 生成到頁(yè)面中
<script>
????????function?getRandom(min,?max)?{
????????????//最小值-最大值的隨機(jī)數(shù)(包含最小值和最大值)
????????????return?Math.floor(Math.random()?*?(max?-?min?+?1))?+?min
????????}
????????let?arr?=?['趙云',?'黃忠',?'關(guān)羽',?'張飛',?'馬超',?'劉備',?'曹操',?'pink老師']
????????//生成隨機(jī)數(shù)
????????let?random?=?getRandom(0,?arr.length?-?1)
????????console.log(random);
????????//渲染到頁(yè)面
????????document.write(arr[random])
????????//?document.write(arr[random])
????????//從數(shù)組里刪除這個(gè)元素
????????arr.splice(random,?1)
????????//渲染到控制臺(tái)
????????console.log(arr)
????</script>