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('恭喜你!猜到了');
    }
}
发布了2 篇原创文章 · 获赞 0 · 访问量 28

猜你喜欢

转载自blog.csdn.net/qq_44398237/article/details/104651482
今日推荐