Math对象
// Math数学对象 不是一个构造函数,所以我们不需要new 来调用 二手在建瓯空额使用里面的属性和方法即可
console.log(Math.PI); // 一个属性 圆周率
console.log(Math.max(1, 99, 3)); // 99
// 案例 利用对象封装自己的数学对象 里面有 PI 最大值和最小值
var myMath = {
PI: 3.141592653,
max: function() {
var max = arguments[0];
for (var i = 1; i < arguments.length; i++) {
if (arguments[i] > max) {
max = arguments[i];
}
}
return max;
}
min: function() {
var min = arguments[0];
for (var i = 1; i < arguments.length; i++) {
if (arguments[i] < min) {
min = arguments[i];
}
}
return min;
}
}
Math 概述
Math 对象不是构造函数,它具有数学常数和函数的属性和方法,跟数学相关的运算(求绝对值,取整,最大值等)可以使用Math中的成员。
Math.PI // 圆周率
Math.floor() // 向下取整
Math.ceil() // 向上取整
Math.round() // 四舍五入版 就近取整 注意 -3.5 结果是 -3
Math.abs() // 绝对值
Math.max() / Math.min() // 求最大和最小值
// (1) Math.floor() 向下取整 往最小了取值
console.log(Math.floor(1.1)); // 1
console.log(Math.floor(1.9)); // 1
// (2) Math.ceil() 向上取整 往最大了取值
console.log(Math.ceil(1.1)); // 2
console.log(Math.ceil(1.9)); // 2
// (3) Math.round() 四舍五入,但是 .5 特殊 它往大了取
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
Math对象随机方法 random()
// 1.Math对象随机方法 random() 返回一个随机的小数 0 =< x <1
// 2.这个方法里面不跟参数
// 3.代码验证
console.log(Math.random());
// 4.我们想要得到两个数之间的随机整数 并且 包含这2个整数
// Math.floor(Math.random() * (max - min + 1) + min);
function getRandom(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
console.log(getRandom(1, 10));
// 5.随机点名
var arr = ['张三', '张三疯', '李思思', '李四', 'fdees'];
console.log(arr[getRandom(0, arr.length - 1)]);
// 猜数字游戏
// 1.随机生成一个 1~10 的整数 我们需要用到Math.random() 方法
// 2.需要一直猜到正确为止,所以需要一直循环。
// 3.while 循环更简单
// 4.核心算法:使用 if else if 多分支语句来判断大于、小于、等于
// 方法一
function getRandom(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
var random = getRandom(1, 10);
while (true) { // 死循环
var num = prompt('你来猜?输入1~10之间的一个数字');
if (num > random) {
alert('你才大了');
} else if (num < random) {
alert('你猜小了')
} else {
alert('你猜对了');
break; // 退出整个循环
}
}
// 猜数字游戏
// 方法二
function getRandom(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
var userInput = prompt('请输入一个数字');
var random = getRandom(1, 10);
console.log(random);
for (var i = 0; i < 5; i++) {
if (userInput < 1 || userInput > 10) {
userInput = prompt('请输入十以内的数');
continue;
}
if (userInput < random) {
alert('数字小了继续猜');
userInput = prompt('请输入十以内的数');
continue;
} else if (userInput > random) {
alert('数字大了继续猜');
userInput = prompt('请输入十以内的数');
continue;
} else if (userInput = random) {
alert('猜对了');
break;
}
}