JavaScript Math Random
Blogs20142014-06-12
JavaScript Math Random
The following are some of my codes to customize random data.
//1. use closure to get current-data.
var current_date = (function() {
var d = new Date();
return new Date(d - d % 86400000).toJSON().slice(0,10);
})();
// current_date is: "2014-06-12"
// 2. get a random range:
var range = function(min, max) {
return ~~(Math.random() * (max - min + 1)) + min
};
range(1,7) // 6
range(100,200) // 160
range(100,200) // 183
//3. get a random in a customized range.
var random = function(num) {
num = parseInt(num) || 100;
return Math.floor((Math.random() * num) + 1);
};
random(100); // 28
random(100); // 56
random(10); // 8
random('abc'); //75
// 4. and a way to call overwritten prototype method.
function M() {}
var m = new M();
M.prototype.say = function() { console.log('prototype say'); }
m.say = function(){
console.log('instance say');
typeof m.__proto__.say=='function' && m.__proto__.say();
};
m.say();
//Output: instance say, prototype sayIt will make processing and testing much easier when using these kind of functions.
