Math 数字对象 Javascript

Math();
数字型内置对象 如果有非数字的,返回NaN 如果为空返回-Infinity(负无穷大)

console.log(Math.max(456, 6, 488)); //输出最大值 488
console.log(Math.PI); //输出圆周率 3.1415926
console.log(Math.max()); //-Infinity  空的为负无穷大

//绝对值

 console.log(Math.abs(-5)); //绝对值 负转正 5
 console.log(Math.abs('-5')); // 隐式转换  5

//数字取整

console.log(Math.floor(2.9)); //往小的取  2
console.log(Math.ceil(2.1)); //往大的取  3
console.log(Math.round(-2.5)); //四舍五入 -2 负数的 .5 除外会往大的取

区别: 自己写的数字对象 用 arguments
//封装数字对象

 var myMath = {
        PI: 3.1415926,
        max: function() { //最大 方法
            var max = arguments[0];
            for (var i = 1; i < arguments.length; i++) {
                if (max < arguments[i]) {
                    max = arguments[i];
                }
            }
            return max;
        },
        min: function() { //最小 方法
            var min = arguments[0];
            for (var i = 1; i < arguments.length; i++) {
                if (min > arguments[i]) {
                    min = arguments[i];
                }
            }
            return min;
        }
    }
    console.log(myMath.PI);
    console.log(myMath.max(123, 321, 0));
    console.log(myMath.min(56, 789, 15));

Math里的random()方法 :随机数方法 (抽奖/随机点名)

  Math.floor(Math.random() * (max - min + 1)) + min;   公式
  document.write(parseInt(Math.random() * 100 + 1)); //1-100的随机数
//小案例  猜数字
for (var i = 1; i <= 10; i++) {
    var sum = prompt('输入一个1-10的数,你有十次机会');
    var shu = parseInt(Math.random() * 10 + 1);
    if (sum > shu || sum < shu) {
        alert('太遗憾了!这个数字是' + shu);
    } else {
        alert('恭喜你!猜到了');
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值