JS学习之内置对象--math对象

内置对象--math对象 > // //Math数学对象 不是一个构造函数,所以不需要new来调用而是直接使用 // //里面的属性和方法即可 // console.log(Math.PI); //属性Math和PI都要大写 // console.log(Math.max(1,2,5,89,56,55,89)); // console.log(Math.max(1,2,5,'pink老师',56,55)); //有非数字的返回NaN // console.log(Math.max()); //返回 -Infinity // 案例:封装自己的数学对象, // 利用对象封装自己的数学对象,里面有PI最大值最小值 // var myMath = { //PI: 3.141592653, //max: function(){ //var max = arguments[0]; //for(var i = 0; i <= arguments.length; i++){ //if(arguments[i] > max){ //max = arguments[i]; //} //} //return max; //}, //min: function(){ //var min = arguments[0]; //for(var i = 0; i <= arguments.length; i++){ //if(arguments[i] < min){ //min = arguments[i]; //} //} //return min; //} // } // console.log(myMath.PI); // console.log(myMath.max(1,2,5,9,68)); //console.log(myMath.min(1,2,5,9,68)); //1.绝对值方法 // console.log(Math.abs(1)); // console.log(Math.abs(-1)); // console.log(Math.abs('1')); //隐式转换把字符串型转换为数字型 // console.log(Math.abs('pink')); //NaN // //2.三个取整方法 // (1)Math.floor()//floor 地板向下取整(往小了取) // console.log(Math.floor(1.1)); //1 // console.log(Math.floor(1.9)); //1 // (2)Math.ceil() ceil 天花板 向上取整(往大了取) // console.log(Math.ceil(1.1)); //2 // console.log(Math.ceil(1.9)); //2 // (3)Math.round() 四舍五入 // console.log(Math.round(1.1)); //1 // console.log(Math.round(1.5)); //2 // console.log(Math.round(1.9)); //2 // console.log(Math.round(-1.1)); //-1 // console.log(Math.round(-1.5)); //-1(按道理来说应该是-2) //PS:Math.round()对于其他数字都是四舍五入,但是对于.5是往大了取 // (4)Math.random()返回一个随机的小数(0 =< x <= 1) // 1.Math.random()返回一个随机小数 // 2.这个方法不跟参数 // 3.返回一个随机的小数(0 =< x <= 1) // 4.要是想得到两个数字之间的随机数并且包含这两个数 //Math.floor(Math.random()*(max - min + 1)) + min; //5.代码验证 // function getRandom(min,max){ //return Math.floor(Math.random() * (max - min +1)) + min; // } // console.log(getRandom(1,100)); //6.随机点名 // var arr = ['张三','李四','王五','赵六','孙七','钱八','周九']; // function getRandom(min,max){ //return Math.floor(Math.random() * (max - min + 1)) + min; // } // //console.log(getRandom(arr[getRandom(0,6)])); // console.log(arr[getRandom(0,arr.length - 1)]); // 案例:猜数字游戏, // 程序随机生成一个1-10之间的数字,并让用户输入一个数字 // 1.如果大于该数字,就提示数字大了,继续猜; // 2.如果小于该数字,就提示数字小了,继续猜; // 3.如果等于该数字,就提示猜对了,结束程序; // function getRandom(min,max){ //return Math.floor(Math.random() * (max - min + 1)) + min; // } // var num_1 = getRandom(1,10); // while(true){ //var num_2= prompt('请输入一个数字'); // if(num_1 > num_2){ //alert('数字小了,继续猜'); // } // else if(num_1 < num_2){ //alert('数字大了,继续猜'); // } // else{ //alert('猜对了'); //break; //退出整个循环 // } // } //要求用户猜1-50之间的一个数字但是只有10次机会 function getRandom(min,max){ return Math.floor(Math.random() * (max - min + 1)) + min; } var num_1 = getRandom(1,50); for(i = 1; i <= 10; i++){ var num_2= prompt('请输入一个数字'); if(num_1 > num_2){ alert('数字小了,继续猜'); } else if(num_1 < num_2){ alert('数字大了,继续猜'); } else if(num_1 == num_2){ alert('猜对了'); break; //退出整个循环 }}

    推荐阅读