JS内置对象和Math对象知识点详解

<script> // Math数学对象 不是一个构造函数 ,所以我们不需要new 来调用 而是直接使用里面的属性和方法即可 console.log(Math.PI); // 一个属性 圆周率 console.log(Math.max(1, 99, 3)); // 99 console.log(Math.max(-1, -10)); // -1 console.log(Math.max(1, 99, 'pink老师')); // NaN console.log(Math.max()); // -Infinity </script>

自己封装对象

<script> // 利用对象封装自己的数学对象 里面有 PI 最大值和最小值 var myMath = { PI: 3.141592653, max: function() { var max = arguments[0]; for (var i = 1; i < arguments.length; i++) { if (arguments[i] > max) { max = arguments[i]; } } return max; }, min: function() { var min = arguments[0]; for (var i = 1; i < arguments.length; i++) { if (arguments[i] < min) { min = arguments[i]; } } return min; } } console.log(myMath.PI); console.log(myMath.max(1, 5, 9)); console.log(myMath.min(1, 5, 9)); </script>

一些常用的方法

<script> // 1.绝对值方法 console.log(Math.abs(1)); // 1 console.log(Math.abs(-1)); // 1 console.log(Math.abs('-1')); // 隐式转换 会把字符串型 -1 转换为数字型 console.log(Math.abs('pink')); // NaN // 2.三个取整方法 // (1) Math.floor() 地板 向下取整 往最小了取值 console.log(Math.floor(1.1)); // 1 console.log(Math.floor(1.9)); // 1 // (2) Math.ceil() ceil 天花板 向上取整 往最大了取值 console.log(Math.ceil(1.1)); // 2 console.log(Math.ceil(1.9)); // 2 // (3) Math.round() 四舍五入 其他数字都是四舍五入,但是 .5 特殊 它往大了取 console.log(Math.round(1.1)); // 1 console.log(Math.round(1.5)); // 2 console.log(Math.round(1.9)); // 2 console.log(Math.round(-1.1)); // -1 console.log(Math.round(-1.5)); // 这个结果是 -1 </script>

<script> // 1.Math对象随机数方法 random() 返回一个随机的小数 0 =< x < 1 // 2. 这个方法里面不跟参数 // 3. 代码验证 console.log(Math.random()); // 4. 我们想要得到两个数之间的随机整数 并且 包含这2个整数 // Math.floor(Math.random() * (max - min + 1)) + min; function getRandom(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } console.log(getRandom(1, 10)); // 5. 随机点名 var arr = ['张三', '张三丰', '张三疯子', '李四', '李思思', 'pink老师']; // console.log(arr[0]); console.log(arr[getRandom(0, arr.length - 1)]); </script>

到此这篇关于JS内置对象和Math对象知识点详解的文章就介绍到这了,更多相关JS内置对象和Math对象内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/aaae0d28cd5e7e00416c7c12e5d0d550.html