js向上取整、向下取整、四舍五入
1)只保留整數(shù)部分
parseInt(2.345) ;? // 2
2)? 向下取整
Math.floor(2.345); //? 2
3) 向上取整
Math.ceil(2.345); // 3
4) 四舍五入
Math.round(2.345); //2
Math.round(2.567); // 3
5) 絕對值
Math.abs(-1); //1
6返回兩者中的較大值
Math.max(1,2); //2
7)返回兩者中的較小值
Math.min(1,2); //1
8)隨機數(shù)(0-1)
Math.random();
應(yīng)用一:如何獲取到[1,10]的隨機數(shù)
方法一:
var number = Math.round(Math.random() * 10);
console.log(number);
方法二:
var num = Math.floor(Math.random()*10) +1;
console.log(num);
應(yīng)用二:如何獲取到[1-10]的隨機數(shù)不重復(fù)
? var arr = [];
? ? var maxTimes = 50;
? ? do{
? ? ? ? var num = Math.floor(Math.random()*10)+1;
? ? ? ? if(-1 == arr.indexOf(num)){
? ? ? ? ? ? arr.push(num);
? ? ? ? }
? ? ? ? maxTimes--;
? ? }while (maxTimes);
? ? console.log(arr);