JavaScript中的Math对象使用方法

·Math对象

值得注意的一点,与其他全局对象不同的是,Math不是一个构造器。Math的所有属性和方法都是静态的。(非构造函数)

静态变量——指的是在程序执行前系统就已经给这个变量分配了一定的存储空间,在运行时也不再改变分配情况

1.绝对值方法

console.log(Math.abs(1));//1
console.log(Math.abs(-1));//1
console.log(Math.abs('-1'));//1 隐式转换 会把字符型转换为数字型
console.log(Math.abs('pinl'));//NaN

2.三个取整方法

//(1)Math.floor() 向下取整 往小的取
console.log(Math.floor(1.1));//1
console.log(Math.floor(1.9));//2
//(2)Math.ceil() 向上取整 往大的取
console.log(Math.ceil(1.1));//2
console.log(Math.ceil(1.9));//2
//(3)Math.round 四舍五入
console.log(Math.round(1.4));//1
console.log(Math.round(2.6))//3

3.随机数方法 random()

作用:随机生成一个[0,1)内的浮点数

得到一个两数之间的随机整数*(抽奖案例)*

function getRandomInt(min,max){
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min; //不含最大值,含最小值
}

那么如果也要取到最大值呢?

我们想要得到两个数之间的随机整数 并且 包含这两个整数

function getRandomInt(){
return Math.floor(Math.random()*(max - min + 1) + min;

随机点名案例

function getRandomInt(){
return Math.floor(Math.random()*(max-min+1)+min;
}
var arr = ['张三','小明','李四','小欧','小华'];
console.log(arr[Math.getRandomInt(0,arr.length-1)]);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值