最大值与最小值
var max = Math.max(3, 54, 32, 16);
console.log(max); //54
var min = Math.min(3, 54, 32, 16);
console.log(min); //3
指定范围内的随机数
var num = Math.floor(Math.random() * 10 + 1);
console.log(num); //a number between 1 and 10
var num = Math.floor(Math.random() * 9 + 2);
console.log(num); //a number between 2 and 10
function selectFrom(lowerValue, upperValue) {
var choices = upperValue - lowerValue + 1;
return Math.floor(Math.random() * choices + lowerValue);
}
var num = selectFrom(2, 10);
console.log(num); //number between 2 and 10 (包含10)
var colors = ["red", "green", "blue", "yellow", "black", "purple", "brown"];
var color = colors[selectFrom(0, colors.length-1)];
console.log(color); //any of the strings in the array
向上取整、向下取整、四舍五入
console.log(Math.ceil(25.9)); //26
console.log(Math.ceil(25.5)); //26
console.log(Math.ceil(25.1)); //26
console.log(Math.round(25.9)); //26
console.log(Math.round(25.5)); //26
console.log(Math.round(25.1)); //25
console.log(Math.floor(25.9)); //25
console.log(Math.floor(25.5)); //25
console.log(Math.floor(25.1)); //25