Math API

1. Note

1.1. Math Constructor

  • Unlike other global objects, the Math object has no constructor. Methods and properties are static.

2. Math Properties (內建常數)

console.log(Math.PI);    // 3.141592653589793

Math.E        // returns Euler's number
Math.PI       // returns PI
Math.SQRT2    // returns the square root of 2
Math.SQRT1_2  // returns the square root of 1/2
Math.LN2      // returns the natural logarithm of 2
Math.LN10     // returns the natural logarithm of 10
Math.LOG2E    // returns base 2 logarithm of E
Math.LOG10E   // returns base 10 logarithm of E

3. Round

3.1. round()

3.2. ceil()

3.3. floor()

四捨五入、無條件進位、無條件捨去

Math.round(4.7);    // returns 5
Math.round(4.4);    // returns 4

Math.ceil(4.4);     // returns 5

Math.floor(4.7);    // returns 4

4. Mix & Max

4.1. min()

4.2. max()

console.log( Math.min(0, 150, 30, 20, -8, -200) );    // -200
console.log( Math.max(0, 150, 30, 20, -8, -200) );    // 150

5. Other Basis

5.1. pow()

次方

Math.pow(8, 2);        // returns 64

5.2. sqrt()

平方

Math.sqrt(64);      // returns 8

5.3. abs()

絕對值

Math.abs(-4.7);     // returns 4.7

6. Random

6.1. random()

returns a random float number between 0 (inclusive), and 1 (exclusive):

(0~1的浮點數,不包含1)

for (i = 0; i < 10; i++) {
    console.log( Math.random() ); // e.g. 0.041695426644897005
}

6.2. Example: Random Integers

Math.random() used with Math.floor() can be used to return random integers.

console.log( Math.floor(Math.random() * 11) ); // 0~10
console.log( Math.floor(Math.random() * 10) ); // 0~9
console.log( Math.floor(Math.random() * 100) ); // 0~99
console.log( Math.floor(Math.random() * 101) ); // 0~100
console.log( Math.floor(Math.random() * 10) +1 ); // 1~10
console.log( Math.floor(Math.random() * 100) +1 ); // 1~100

6.3. Example: Random in Range

// between min (included) and max (excluded):
function getRndInteger(min, max) {
    return Math.floor(Math.random() * (max - min) ) + min;
}

// between min and max (both included):
function getRndInteger(min, max) {
    return Math.floor(Math.random() * (max - min + 1) ) + min;
}

7. 三角函數

7.1. sin()

7.2. cos()

Math.sin(90 * Math.PI / 180);     // returns 1 (the sine of 90 degrees)
Math.cos(0 * Math.PI / 180);     // returns 1 (the cos of 0 degrees)

results matching ""

    No results matching ""