HTML
导入代码模板:
Random.js
Introduction
Working with JavaScript, you may have noticed the absolute lack of random methods. Well don't worry! I've created a very very simple plugin to extend current random methods! (I know this already exists, but here is my version)
Instructions
Math.randomInt(min, max)
This gets a random integer between the min
and max
values
Math.randomInt(0, 10)
Click the button!
Math.randomDec(min, max, decimals)
This gets a random decimal number between the min
and max
values, precision to decimals
Math.randomDec(0, 10, 2)
Click the button!
Math.randomList(list)
This chooses a random value from an array list
Math.randomList(['doge', 'cate', 'snek'])
Click the button!
Usage
Plop this at the start of your code
(function () {
Math.randomInt = function (min, max) {
return Math.floor(Math.random() * (max - min)) + min;
};
Math.randomDec = function (min, max, decimals) {
return (Math.random() * (max - min) + min).toFixed(decimals || 2);
};
Math.randomList = function (list) {
return list[Math.randomInt(0, list.length)];
};
})();