JavaScript အရေးပါ
Math.random()
Math.random()
0 (ပါ) မှ 1 (မပါ) အထိ သုံးသပ်သော နေရာ ပြန်လည် ပေးသည်:
实例
Math.random(); // သုံးသပ်သော နေရာ ပြန်လည် ပေးသည်
Math.random()
အချိန်ကတည်းက 1 အောက် သုံးသပ်သော နေရာ ပြန်လည် ပေးသည်。
ဂျူနော်စ် သုံးသပ်သော အကြမ်းအား
Math.random()
နှင့် Math.floor()
သုံးသပ်သော အကြမ်းအား ပြန်လည် ပေးရန် အသုံးပြုသည်。
实例
Math.floor(Math.random() * 10); // ပြန်လည် 0 မှ 9 အထိ သုံးသပ်သော နေရာ
实例
Math.floor(Math.random() * 11); // ပြန်လည် 0 မှ 10 အထိ သုံးသပ်သော နေရာ
实例
Math.floor(Math.random() * 100); // ပြန်လည် 0 မှ 99 အထိ သုံးသပ်သော နေရာ
实例
Math.floor(Math.random() * 101); // 返回 0 至 100 之间的数
实例
Math.floor(Math.random() * 10) + 1; // 返回 1 至 10 之间的数
实例
Math.floor(Math.random() * 100) + 1; // 返回 1 至 100 之间的数
一个适当的随机函数
正如你从上面的例子看到的,创建一个随机函数用于生成所有随机整数是一个好主意。
这个 JavaScript 函数始终返回介于 min
(包括)和 max
(不包括)之间的随机数:
实例
function getRndInteger(min, max) { return Math.floor(Math.random() * (max - min) ) + min; }
这个 JavaScript 函数始终返回介于 min
和 max
(都包括)之间的随机数:
实例
function getRndInteger(min, max) { return Math.floor(Math.random() * (max - min + 1) ) + min; }