
Math数学对象 不是一个构造函数,所以我们不需要new来调用 而是直接使用里面的属性和方法即可
1.圆周率console.log(Math.PI);
2.最大值
console.log(Math.max(1, 99, 3));//99
console.log(Math.max(-1, -10));//-1
console.log(Math.max(1, 99,'pink老师'));//NaN
返回给定的一组数字中的最大值。如果给定的参数至少有一个参数无法转换成数字,则会返回NaN
console.log(Math.max());
如果没有参数则结果为-Infinity
3.最小值 console.log(Math.min(1, 99, 3))//输出1
4.绝对值方法
console.log(Math.abs(1));//1
console.log(Math.abs(-1));//1
console.log(Math.abs('-1'));//隐式转换 会把字符串型 -1 转换为数字型 1
console.log(Math.abs('pink'));//1
5.取整方法
(1)Math.floor( ) 向下取整 往最小了取值
console.log(Math.floor(1.2));//1
console.log(Math.floor(1.9));//1
(2)Math.ceil( ) 向上取整 往最大了取值
console.log(Math.ceil(1.9));//2
console.log(Math.ceil(1.1));//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(往大了取)
6.math对象随机数方法
(1)随机生成一个小数
random()返回一个随机的小数 0 =< x <1
这个方法里面不跟参数
console.log(Math.rondom());
(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, 56));
例题:
随机点名:
var arr = ['张三', '张四', '张武', '张柳']
console.log(arr[getRandom(0, arr.length - 1)]);
猜数字游戏(猜1-30之间的数字,共有5次机会):
function getRandom(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
var random = getRandom(1,30)
for(var i = 0; i < 5; i++) {
var num = prompt('请输入1-30之间的一个数字');
if (num > random) {
alert('猜大了');
} else if (num < random) {
alert('猜小了');
} else if (num = random) {
alert('猜对了');
break;//结束整个循环
}
}
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)