js Math汇总

// ----------  JavaScript Math  ----------

// 

// abs(x)
// 返回x的绝对值
// Math.abs(x)
console.log( Math.abs(8.8) ); // 8.8
console.log( Math.abs(-8.8) ); // 8.8
console.log( Math.abs(null) ); // 0
console.log( Math.abs(undefined) ); // NaN
console.log( Math.abs('121') ); // 121
console.log( Math.abs(6 + 6) ); // 12
console.log( Math.abs(NaN) ); // NaN

// ceil(x)
// 进行向上舍入
//  Math.ceil(x)
console.log( Math.ceil(0.9) ); // 1
console.log( Math.ceil(1.6) ); // 2
console.log( Math.ceil(16.6) ); // 17
console.log( Math.ceil(-1.6) ); // -1
console.log( Math.ceil(-16.6) ); // -16

// floor(x)
// 进行向下舍入, 返回小于等于x的最大整数
// Math.floor(x)
console.log( Math.floor(0.9) ); // 0
console.log( Math.floor(1.6) ); // 1
console.log( Math.floor(16.6) ); // 16
console.log( Math.floor(-1.6) ); // -2
console.log( Math.floor(-16.6) ); // -17

// max(x,y,z,...,n)
//     返回 x,y,z,...,n 中的最高值
// Math.max(n1,n2,n3,...,nX)
console.log( Math.max(1, 2, 3, 4, 4, 5, 6, 7, 8) ) // 8
console.log( Math.max(-1, -2, -3, -4, -4, -5, -6, -7, -8) ) // -1

// min(x,y,z,...,n)
// 返回 x,y,z,...,n中的最低值
// Math.min(n1,n2,n3,...,nX)
console.log( Math.min(1, 2, 3, 4, 4, 5, 6, 7, 8) ) // 1
console.log( Math.min(-1, -2, -3, -4, -4, -5, -6, -7, -8) ) // -8


// pow(x,y)
// 返回 x 的 y 次幂
// Math.pow(x,y)
console.log(Math.pow(2, 3)) // 8
console.log(Math.pow(1, 30000)) // 1
console.log(Math.pow(-3, 3)) // -27


// random()
// 返回 0(含) ~ 1(不含) 之间的随机数
// Math.random()
console.log( Math.random() ) // 0.29444001804261943 (随机)
console.log( Math.floor( ( Math.random() * 100 ) + 1) ) // 1 - 100随机数

  // 返回返回 min(含) - max(不含) 之间的书任意数
function getRndInteger(min, max) {
  return Math.floor( Math.random() * (max - min) ) + min;
}
console.log( getRndInteger(5, 10) ) // 5

  // 返回返回 min(含) - max(含) 之间的书任意数
function getRndInteger(min, max) {
  return Math.floor( Math.random() * (max - min + 1) ) + min;
}
console.log( getRndInteger(5, 10) ) // 9


// round(x)
// 四舍五入, 舍入最接近的数
// Math.round(x)
console.log( Math.round(2.3) ) // 2
console.log( Math.round(2.5) ) // 3
console.log( Math.round(0) ) // 0
console.log( Math.round(-2.3) ) // -2
console.log( Math.round(-2.5) ) // -2
console.log( Math.round(-2.6) ) // -3


// sqrt(x)
// 返回数的平方根
// Math.sqrt(x)
console.log( Math.sqrt(4) ) // 2
console.log( Math.sqrt(9) ) // 3
console.log( Math.sqrt(16) ) // 4
console.log( Math.sqrt(-9) ) // NaN

 

posted @ 2023-04-07 16:14  王希有  阅读(53)  评论(0编辑  收藏  举报