[Related recommendations: JavaScript video tutorials, web front-end]
The Math object is not a constructor, it has the properties and methods of mathematical constants and functions. Math-related operations (absolute value, rounding, maximum value, etc.) can use members in Math.
Math.PI //Pi
Math.floor () //Rounding down
Math.ceil () //Rounding up
Math.round () //Rounding to the nearest integer Note - 3.5 The result is - 3
Math.abs () //Absolute value
Math.max ()/Math.min() //Find the maximum and minimum values
Math.random() //Return a random decimal 0=<x<1(this method There are no parameters in it)
//1. Absolute value method console.log(Math.abs(1)); // 1 console.log(Math.abs(-1)); //1 console.log(Math.abs('-5')); //5 will be implicitly converted, convert the numeric string into a number, and then take the absolute value console.log(Math.abs('aniu')); / /NaN
//2. Three rounding methods console.log(Math.floor(1.1)); //1 console.log(Math.floor(1.9)); //1 console.log(Math.floor(-1.1)); //-2 console.log(Math.ceil(1.1)); // 2 console.log(Math.ceil(1.9)); //2 console.log(Math.ceil(-1.9)); //-1 console.log(Math.round(1.5)); //2 This special rounding of .5 is to take the larger console.log(Math.round(-1.5)); // -1 to take the console.log to the larger one. (Math.round(-1.2)); // -1
//3. Find the maximum/minimum value console.log(Math.max(1,5,78,46)); console.log(Math.min(1,5,78,46));
//4. Random number console.log(Math.random());
Find a random integer between two numbers and contain these two numbers:
//core algorithm
Math.floor(Math.random()*(max-min)) + min;
function getRandom(min,max){ return Math.floor(Math.random()*(max-min)) + min; } console.log(getRandom(1,7));
//Random roll call var arr = ['Aniu','Mengmeng','Little Naruto','winter','Xiao He','WA','Bit God', 'Zawa'] //Too many, just write these examples console.log(arr); console.log('Aniu loves you???'); function getRandom(min,max){ return Math.floor(Math.random()*(max-min)) + min; } console.log('Random point hit:' + arr[getRandom(0,arr.length - 1)]);
[Related recommendations: JavaScript video tutorials, web front-end]
The above is the detailed content of the JavaScript built-in object Math instance sharing. For more information, please pay attention to other related articles on the source code network!