[笔记][JavaScript] - 随机取出阵列元素之值

目的:能产生简易版本乱数抽签系统

先从 Math.random() 语法了解

再带入至 Math.floor() 让每个被取出物件机率都相同

再用 Javascript 把对应的 array 元素取出显示在指定标签中

Math.random()

会回传介於0到1之间(包含 0,不包含1) 的伪随机数字

大致符合数学与统计上的均匀分布

function getRandom() {
  return Math.random();
}

//此方法不符合加密学安全性要求。请勿使用於任何加密、资安相关领域。
//详请请见:https://zhuanlan.zhihu.com/p/205359984

随机取出两数值之间值(不包含最大值)

The returned value is no lower than (and may possibly equal) min, and is less than (and not equal) max.

返回的值大於等於 最小值 min,且小於 最大值 max

e.g A, B, C, D, E, F, G

回传数值区间包含A,不包含G

function getRandomArbitrary(min, max) {
  return Math.random() * (max - min) + min;
}

Math.floor()

将所有的小数无条件舍去到比该值小的最大整数

有点绕口但其实就是高斯符号的取底

console.log(Math.floor(5.9999));
// expected output: 5

console.log(Math.floor(-5.05));
// expected output: -6

所以结合起来 Math.floor(Math.random()*7-0 + 0);

会回传 0 到 6 (包含0跟6)其中一个『整数』

每个数字选中机率都一样,所以可以拿来做抽签

那个数字七也就代表阵列的长度

第几位抽到就是 回传值+1

Math.ceil()

取大於的最小整数

console.log(Math.ceil(.95));
// expected output: 1

console.log(Math.ceil(4));
// expected output: 4

首尾数值都包含且取整数

例如取得 4.9 到 9.9 之间的一个整数
5,6,7,8,9

整数用 floor, 包含最大值 +1

function getRandomIntInclusive(min, max) {
  min = Math.ceil(min);
  // min = 5     
  max = Math.floor(max);
  // max = 9 
  return Math.floor(Math.random() * (max - min + 1) + min); 
    // Math.floor(Math.random()*5 + 5
}

假设有一阵列

array=[one,two,three,four];

随机取出一位即为

<p id="demo0"></p>
<p id="demo1"></p>

randomData()

function randomData(){

let x = Math.floor(Math.random() * data.length);
let y = x + 1;
document.getElementById("demo0").innerHTML = "第几位:" + y;
document.getElementById("demo1").innerHTML = "中奖人:" + array[x];
}

效果预览:https://wastu01.github.io/Javascript-Random-from-array/

完整程序码:https://codepen.io/mrwang01/pen/jOYbXQQ

以上同步至个人学习日志:https://hackmd.io/@DCT/随机乱数抽签系统

参考资料:

Math.random()语法说明:
https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Math/random

用Math.random()取得乱数的技巧
https://ithelp.ithome.com.tw/articles/10197904#_=_

<< 我的第一篇it邦文章 :) >>


<<:  K8s 在 DevOps 中的作用

>>:  16. STM32-I²C EEPROM DataSheet

[FGL] OPEN WINDOW WITH 画面档

前几个篇章中,若使用到客户端 (如GDC/GBC) 呈现画面时,Hello World 都只能出现...

【Day 22】ECS Task Definitions and setting of ECS provider

tags: 铁人赛 AWS Outposts ECS 今天直接接续昨天部分说明 调整 Cluster...

Day16 测试与进度计算,与客诉的关系

谈到专案测试,最常听到的一句话就是「你测过了没?」与「这跟我测的时候不一样」这两句经典台词。 在谈到...

Day 12:想要快速产出元件及范本,就用 Angular CLI 吧!(二)

让 Angular 元件显示在画面上 上一篇,我们建立了一个元件 page1。 接下来,我们就要把 ...

Day12 CSS基础设定介绍_1

文字及字体 文字大小及字体是我们在网页中最常设定跟调整的,在预设的字体中你可能找不到你想要的字体类型...