第十一节:Math对象

一.Math对象

Math 对象: 是js内置的一个操作数据的对象,就是做数学运算的一个对象;

1.random随机生成0-1直接的数字,包含0,不包含1

// 语法 : Math.random();
var res = Math.random();
console.log(res);
// 0-10 之间的随机数
var res = parseInt( Math.random()*10);
console.log(res);
// 10-20之间的数 
var res = parseInt( Math.random()*10+10);
console.log(res);
// 30-40 之间的随机数
var res = parseInt( Math.random()*10+30);
console.log(res);
// 20-40之间的随机数 
var res = parseInt( Math.random()*20+20);
console.log(res);
// 0-40
var res = parseInt(Math.random()*40);
console.log(res);

// min-max之间的随机数 ???(包前不包后)
var min = 10,max = 20;
var res = parseInt( Math.random()*(max-min)+min);
console.log(res);
// //  min-max之间的随机数 ???(包前也包后)
var min = 1,max = 9;   
// min=1 max = 9  ---> 1..8; 现在我想 得到 1..9 的数 可以把范围设置 1-10
var res = parseInt( Math.random()*(max+1-min)+min);
console.log(res);

// 可以封装一个随机函数 ,可以随机生成 一个 min-max之间的数 (包含min也包含max);
function  randomNum(min,max) {
    return parseInt( Math.random()*(max+1-min)+min);
}

2.round:四舍五入

var a = 1.3;
var res =  Math.round(a);
console.log(res); // 1

// 概率问题 
 function  randomNum(min,max) {
    // 0-9.9999999999999
    return Math.round(Math.random()*(max-min)+min);
 }
// 0-0.5  ---> 0
// 0.6-1.4999 ---> 1
// 1.5--2.4999--->2
// ....
// 9.5---9.9999---->10
randomNum(0,10) // 通过parseInt 随机出来的数就是 0-9之间的数
Math.round 可以随机出来 0-10之间的数字

3.ceil:向上取整

var a = 1.93434;
var res =  Math.ceil(a);
console.log(res);

4.向下取整:floor

var a = 2.9;
var res = Math.floor(a);
console.log(res);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值