JS取整取余,Math对象的操作方法

所有方法都是属于Math对象的方法

取整

取整

//丢弃小数部分,保留整数部分
parseInt(7/2);  //3

向上取整

//向上取整,有小数就整数部分+1
Math.ceil(7/2);  //4

向下取整

//向下取整,丢弃小数部分
Math.floor(7/2);  //3

四舍五入

//四舍五入
Math.round(7/2);  //4

取余

取余

//取余
7%2;  //1

取最大值和最小值的方法

Math对象中的min()和max()方法可以用于确定一个数组中的最大值和最小值

let max = Math.max(3, 54, 62, 10);
console.log(max);  //62
let min = Math.min(3,54,62,10);
console.log(min);  //3
//对于一个确定的数组,需要使用apply来改变this指针来指向Math对象而不是window对象
let arr = [3,54,62,10];
let max = Math.max.apply(Math,arr);
console.log(max);  //62

random()—取随机数

Math.random()方法返回一个大于等于0而小于1 的一个随机数

let random = Math.random(); // [0,1)

//获取一个1~10之间的整数
let random = Math.floor(Math.random()*10+1);

//编写一个函数,输入取值范围能够输出一个在该范围内的随机数
function selectFrom(lowerValue, upperValue){
    let choices = upperValue - lowerValue;
    return Math.floor(Math.random()*choices + lowerValue);
}
let num = selectFrom(2,10);
console.log(num);  //输出一个2~10(包括2和10)的一个数值

let colors = ['red', 'green', 'blue', 'yellow', 'black', 'purple'];
let color = colors[selectFrom(0,colors.length-1)];
console.log(color); //随机输出一个颜色

toFixed()方法

number.toFixed(num)方法会将number转换为num个小数位的小数,其中num是必需值,如果省略了该值,将用0代替

let num = 12.3335;
console.log(num.toFixed(2));  //12.33

猜你喜欢

转载自blog.csdn.net/qq_31947477/article/details/105832770
今日推荐