- 绝对值方法
// 1. 绝对值方法
console.log(Math.abs(1)); //1
console.log(Math.abs(-1)); //1
console.log(Math.abs("1")); //隐式转换,会把字符串型“-1”转换为数字型
console.log(Math.abs("pink")); //NaN
- 三个取整方法
// 2. 三个取整方法
Math.floor(); //地板,向下取整,往小了取值
console.log(Math.floor(1.1)); //1
console.log(Math.floor(1.9)); //1
Math.ceil(); //天花板,向上取值,往最大了取值
console.log(Math.ceil(1.1)); //2
console.log(Math.ceil(1.9)); //2
Math.round(); //四舍五入 但是0.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
console.log(Math.round(-1.9)); //-2
- Math对象随机数方法 random()返回一个随机的小数 0=<x<1
// 3. Math对象随机数方法 random()返回一个随机的小数 0=<x<1
// 这个方法里面不跟参数
console.log(Math.random());
- 我们想要得到两个数之间的随机整数 并且包含这2个整数
Math.floor(Math.random() * (max - min + 1)) + min
// 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 = ["张三", "李四", "王五", "pink", "沈六", "刘七", "肖八"];
console.log(arr[getRandom(0, arr.length - 1)]);