JavaScript 數學 (Math) 方法
- 2022 年 4 月 18 日
- 筆記
- javascript, JavaScript高級
一、Math 方法
1、Math.round(x)
的返回值是 x 四捨五入為最接近的整數:
Math.round(7.8); // 返回 8
Math.round(3.3); // 返回 3
2、Math.random()
返回介於 0(包括) 與 1(不包括) 之間的隨機數:
Math.random() //返回隨機整數
3、Math.pow(x, y)
的返回值是 x 的 y 次冪:
Math.pow(4, 2); // 返回 16
4、Math.sqrt(x)
返回 x 的平方根:
Math.sqrt(64); // 返回 8
5、Math.ceil(x)
的返回值是 x 上舍入最接近的整數:
Math.ceil(6.4); // 返回 7
6、Math.floor(x)
的返回值是 x 下舍入最接近的整數:
Math.floor(2.7); // 返回 2
7、Math.abs(x)
返回 x 的絕對(正)值:
Math.abs(-4.7); // 返回 4.7
8、Math.min()
和 Math.max()
可用於查找參數列表中的最低或最高值:
Math.min(0, 450, 35, 10, -8, -300, -78); // 返回 -300
Math.max(0, 450, 35, 10, -8, -300, -78); // 返回 450
二、JavaScript 隨機整數
Math.random()
與 Math.floor()
一起使用用於返回隨機整數。
Math.floor(Math.random() * 10); // 返回 0 至 9 之間的數
Math.floor(Math.random() * 11); // 返回 0 至 10 之間的數
Math.floor(Math.random() * 10) + 1; // 返回 1 至 10 之間的數