js use of Math functions

There are many methods of the Math functions used are the following

var arr=[1,2,3,4,5,6]
//最小值
console.log(Math.min(...arr)) //结果: 1

//最大值
console.log(Math.max(...arr))  //结果: 6

//绝对值
console.log(Math.abs(-10))  //结果: 10

//退一取整(向下取整)
console.log(Math.floor(1.9))   //结果: 1

//进一取整(向上取整) 
console.log(Math.ceil(1.1))   //结果: 2

//幂运算 2的3次方
console.log(Math.pow(2,3))   //结果 8

//平方运算  返回一个数的平方根
console.log(Math.sqrt(9))  // 结果 3

Emphasis

Math random number acquisition

Such random number acquired only get a decimal between 0 and 1, to obtain the minimum infinitely close to zero decimal places, but never fail to 0, the maximum decimal infinitely close to 1 is obtained, but also fail to empathy 1

console.log(Math.random());

Thus obtained in the range of (0-9) between theThere decimal numberInfinitely close to the maximum 10This integer

console.log(Math.random()*10)

To obtain the number range (0 to 10), the multiplication and addition 1 to 10 on the basis of

//方法一
console.log((Math.random()*10)+1)
//方法二
console.log(Math.random()*11)
To get a random integer results, to add a method
console.log(Math.floor(Math.random()*11))
To obtain a random integer in the range of (5-10)
console.log(Math.floor(Math.random()*6)+5)

To get a summary of the specified range into a random integer may be packaged using the method according to the law

function random(min,max){
  return Math.floor(Math.random()*(max-min+1))+min
}
console.log(random(10,20))
Published 39 original articles · won praise 13 · views 2320

Guess you like

Origin blog.csdn.net/qq_43205282/article/details/103664469