0
点赞
收藏
分享

微信扫一扫

JavaScript 学习-18.Math数学运算

前言

Math 对象允许您执行数学任务。

Math 不是构造函数。Math 的所有属性/方法都可以通过使用 Math 作为对象来调用,而无需创建它

Math 属性

Math 提供了一些属性,可以快速得到一个数学里面的值,如圆周率π(约为3.14),2的平方根约1.414

const x = Math.PI;            // 返回 PI
const y = Math.SQRT2; // 返回 2 的平方根
console.log(x);
console.log(y);

Math 方法

Math 对象一些常用的方法:

  • abs(x), 返回x的绝对值
  • max(x, y, z, ..., n) 返回最大值
  • min(x, y, z, ..., n) 返回值最小的数字。
  • pow(x, y) 返回 x 的 y 次幂值。
  • round() 返回数字四舍五入到最接近的整数。
  • floor(x) 返回向下舍入为最接近的整数。
  • random() 返回0到1直接随机数

abs(x), 返回x的绝对值

let x = 3;
let y = -4;
let a = Math.abs(x);
let b = Math.abs(y);
console.log(a, b) // 3 4

max(x, y, z, ..., n) 返回最大值

let a = Math.max(2, 5);
let b = Math.max(0, 2, 4, 7, 12);
let c = Math.max(-2, 5);
console.log(a); // 5
console.log(b); // 12
console.log(c); // 5

如何得到一个数组对象里面成员最大值和最小值?

let x = [2, 4, 7, 12];
console.log(Math.max(x)); // NaN
console.log(Math.min(x)); // NaN

如果 Math.max() 直接传数组对象,那么得到的结果是NaN.

max()和min()方法需要传多个参数,而不是一个数组,所以可以用到扩展运算符(...)

let x = [2, 4, 7, 12];
console.log(Math.max(...x)); // 12
console.log(Math.min(...x)); // 2

pow(x, y) 返回 x 的 y 次幂

let x = Math.pow(2, 3);  // 2的3次幂 8
let y = Math.pow(2, 4); // 2的3次幂 16
console.log(x);
console.log(y);

指数运算还可以用到两个星号运算符​​**​

let x = 2**3;
let y = 2**4;
console.log(x); // 8
console.log(y); // 16

round() 返回数字四舍五入到最接近的整数。

四舍五入取整

let a = Math.round(2.60);   // 3
let b = Math.round(2.50); // 3
let c = Math.round(2.49); // 2
let d = Math.round(-2.60); // -3
let e = Math.round(-2.50); // -2
let f = Math.round(-2.49); // -2

floor(x) 返回向下舍入为最接近的整数。

向下舍入取整

let a = Math.floor(0.60);   // 0
let b = Math.floor(0.40); // 0
let c = Math.floor(5); // 5
let d = Math.floor(5.1); // 5
let e = Math.floor(-5.1); // -6
let f = Math.floor(-5.9); // -6

random() 返回随机数

random() 方法返回从 0(含)到 1(不含)的随机数。

let x = Math.random();
let y = Math.random();
console.log(x); // 0.041820330842348596
console.log(y); // 0.8178949610470638

返回 1 到 10 之间的随机整数:

let x = Math.floor((Math.random() * 10) + 1);
console.log(x); // 5

返回 1 到 100 之间的随机整数:

let x = Math.floor((Math.random() * 100) + 1);
console.log(x); // 80




举报

相关推荐

0 条评论