Math数学计算
1.最大最小值
max()
min()
不支持数组作为参数,只支持多数值参数。因此数组使用…展开语法或者apply方法。
console.log(Math.max(1, 2, 3, 4, 5));
console.log(Math.min(1, 2, 3, 4, 5));
let grade = [12, 3, 5, 67, 88];
console.log(Math.max(grade));
console.log(Math.max(...grade));
console.log(Math.max.apply(null, grade));
2.向上向下取整
ceil()
floor()
不是四舍五入!!!
console.log(Math.ceil(5.4));
console.log(Math.floor(5.99));
3.舍入函数
toFixed()
round()
console.log((5.5666).toFixed(2));
console.log(Math.round(5.5666));
4.获取随机数
random()
是获取[0,1)的随机数
console.log(Math.random());
5.范围内随机数
(1)[0,5]
Math.floor(Math.random() * (max + 1))
console.log(Math.floor(Math.random() * (5 + 1)));
(2)[2,5]
min + Math.floor(Math.random() * (max - min + 1))
console.log(2 + Math.floor(Math.random() * (5 - 2 + 1)));
随机点名
const students = ["alison", "ruby", "andy", "yooo"];
// >=0~<=3
let number = Math.floor(Math.random() * students.length);
console.log(students[number]);
// >=1~<=3
let index = 1 + Math.floor(Math.random() * (students.length - 1));
console.log(students[index]);
function arrayRandomValue(array, start = 0, end) {
end = end ? end : array.length;
const index = start + Math.floor(Math.random() * (end - start + 1));
return array[index];
}
// >=2~<=3
console.log(arrayRandomValue(students, 2, 3));