Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Math

1. 静态方法

所有方法都是静态方法,通过 Math 前缀调用

.max()/.min()

let num = 0;
num = Math.max(num, 5);
console.log(num); //5
num = Math.min(num, -5);
console.log(num); //-5

const arr = [1, 2, 3];
const max = Math.max(...arr);
console.log(max); // 3
const min = Math.min(...arr);
console.log(min); // 1

.ceil()/.floor()/.trunc() 取整

const positive = 1.7;
const negative = -1.7;

console.log(Math.ceil(positive)); // 2 正方向寻找天花板
console.log(Math.ceil(negative)); // -1 正方向寻找天花板

console.log(Math.floor(positive)); // 1 负方向寻找地面
console.log(Math.floor(negative)); // -2 负方向寻找地面

console.log(Math.trunc(positive)); // 1 与中间0靠齐
console.log(Math.trunc(negative)); // -1 与中间0靠齐

.pow()/log2()

console.log(Math.pow(2, 3)); // 8,即2的3次方
  • 也可用平方符号**,或者自平方符号**=

    let squared = 2 ** 2;
    let cubed = 2 ** 3;
    
    let a = 2;
    a **= 2; //对a自身做平方
    
    let b = 2;
    b **= 2; //对a自身做立方
    
console.log(Math.log2(8)); // 3,即取8的以2为底的对数
console.log(Math.log2(9)); // 3.169925001442312,可以用floor向下取整