This article brings you relevant knowledge about the javascript built-in object math. It explains the usage of common functions in Math based on examples, including the absolute value method, three rounding methods, etc. Wait, let’s take a look at it together, I hope it will be helpful to everyone.
[Related recommendations: javascript video tutorial, web front-end】
The Math object is not a constructor, it has properties and methods for mathematical constants and functions. Math-related operations (finding absolute values, rounding, maximum values, etc.) can use members in Math.
Math.PI //Pi
//1.绝对值方法 console.log(Math.abs(1)); // 1 console.log(Math.abs(-1)); //1 console.log(Math.abs('-5')); //5 会隐式转换,将数字字符串转换为数字,然后取绝对值 console.log(Math.abs('aniu')); // NaN
2.Three rounding Method
//2.三个取整方法 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 四舍五入 .5这个特殊,是往大了取 console.log(Math.round(-1.5)); // -1 往大了取 console.log(Math.round(-1.2)); // -1
3. Find the maximum/minimum value
//3.求最大值/最小值 console.log(Math.max(1,5,78,46)); console.log(Math.min(1,5,78,46));
4. Random numbers
//4.随机数 console.log(Math.random());
Case - A small algorithm to find a random integer between two numbers (important)
Find a random integer between two numbers and contain these two numbers://Core algorithmMath.floor(Math.random()*(max-min)) min;
function getRandom(min,max){ return Math.floor(Math.random()*(max-min)) + min; } console.log(getRandom(1,7));Copy after login
Case-Random Roll Call (Hey hey hey)
//随机点名 var arr = ['阿牛','梦梦','小鸣人','winter','小何','WA','贱神','扎哇'] //太多啦,就写这些举例啦 console.log(arr); console.log('阿牛爱你们???'); function getRandom(min,max){ return Math.floor(Math.random()*(max-min)) + min; } console.log('随机点中了:' + arr[getRandom(0,arr.length - 1)]);
[Related recommendations:javascript video tutorial
、web front-end】
The above is the detailed content of JavaScript built-in object Math example sharing. For more information, please follow other related articles on the PHP Chinese website!