js中的Math对象

绝对值Math.abs()

    console.log(Math.abs(-25));
    console.log(Math.abs('-25'));//存在隐式转换可以求绝对值
    console.log(Math.abs('wq'));//结果为NaN  not a number

取整Math.floor()  Math.ceil()

    console.log(Math.floor(1.9)); 向下取整  floor意为地板
    console.log(Math.ceil(1.1)); 向上取整 ceil意为天花板

四舍五入Math.round()

    console.log(Math.round(1.5)); 结果为2
    console.log(Math.round(-1.5));  注意当以 .5 结束时,结果往较大数取,所以此结果为-1

随机数函数Math.random()

    function getRandom(min,max){
        return Math.floor(Math.random()*(max-min+1))+min; //随机整数
    }
    console.log(Math.random()); //o到1(包含0)的随机小数
    console.log(getRandom(1,10)); 

 一个猜数字的小游戏

var m=getRandom(1,50); //生成1到50之间的随机数
    for(var i=10;i>0;i--) {
        var n=prompt('请输入你猜的1-50数字呀');
        if(i>1){
            if(m<n){
                alert('你猜大了,'+'还有'+(i-1)+'次机会哦!');
            }
            else if(m>n){
                alert('你猜小了,'+'还有'+(i-1)+'次机会哦!');
            }
            else if(m=n){
                alert('你真棒,猜对了');
                break;
            }
        }else{
                alert('机会用完了哦!');
            }
    }

 

 

posted @ 2019-09-11 19:18  齐齐怪  阅读(905)  评论(0编辑  收藏  举报