JavaScript 中的 Math 物件提供了一組用於執行數學任務的屬性和方法。這是 Math 物件的綜合備忘錄。
屬性
Math 物件有一組常數:
Property |
Description |
Value (Approx.) |
Math.E |
Euler's number |
2.718 |
Math.LN2 |
Natural logarithm of 2 |
0.693 |
Math.LN10 |
Natural logarithm of 10 |
2.302 |
Math.LOG2E |
Base 2 logarithm of Math.E
|
1.442 |
Math.LOG10E |
Base 10 logarithm of Math.E
|
0.434 |
Math.PI |
Ratio of a circle's circumference to its diameter |
3.14159 |
Math.SQRT1_2 |
Square root of 1/2 |
0.707 |
Math.SQRT2 |
Square root of 2 |
1.414 |
方法
1.舍入法
Method |
Description |
Example |
Math.round(x) |
Rounds to the nearest integer |
Math.round(4.5) → 5
|
Math.floor(x) |
Rounds down to the nearest integer |
Math.floor(4.7) → 4
|
Math.ceil(x) |
Rounds up to the nearest integer |
Math.ceil(4.1) → 5
|
Math.trunc(x) |
Removes the decimal part (truncates) |
Math.trunc(4.9) → 4
|
2.隨機數產生
Method |
Description |
Example |
Math.random() |
Generates a random number between 0 and 1 (exclusive) |
Math.random() → 0.53
|
Custom Random Int Generator |
Random integer between min and max
|
Math.floor(Math.random() * (max - min 1)) min |
3.算術方法
Method |
Description |
Example |
Math.abs(x) |
Absolute value |
Math.abs(-7) → 7
|
Math.pow(x, y) |
Raises x to the power of y
|
Math.pow(2, 3) → 8
|
Math.sqrt(x) |
Square root of x
|
Math.sqrt(16) → 4
|
Math.cbrt(x) |
Cube root of x
|
Math.cbrt(27) → 3
|
Math.hypot(...values) |
Square root of the sum of squares of arguments |
Math.hypot(3, 4) → 5
|
4.指數與對數方法
Method |
Description |
Example |
Math.exp(x) |
e^x |
Math.exp(1) → 2.718
|
Math.log(x) |
Natural logarithm (ln(x)) |
Math.log(10) → 2.302
|
Math.log2(x) |
Base 2 logarithm of x
|
Math.log2(8) → 3
|
Math.log10(x) |
Base 10 logarithm of x
|
Math.log10(100) → 2
|
5.三角函數
Method |
Description |
Example |
Math.sin(x) |
Sine of x (x in radians) |
Math.sin(Math.PI / 2) → 1
|
Math.cos(x) |
Cosine of x (x in radians) |
Math.cos(0) → 1
|
Math.tan(x) |
Tangent of x (x in radians) |
Math.tan(Math.PI / 4) → 1
|
Math.asin(x) |
Arcsine of x (returns radians) |
Math.asin(1) → 1.57
|
Math.acos(x) |
Arccosine of x
|
Math.acos(1) → 0
|
Math.atan(x) |
Arctangent of x
|
Math.atan(1) → 0.785
|
Math.atan2(y, x) |
Arctangent of y / x
|
Math.atan2(1, 1) → 0.785
|
6.最小值、最大值與箝位
Method |
Description |
Example |
Math.max(...values) |
Returns the largest value |
Math.max(5, 10, 15) → 15
|
Math.min(...values) |
Returns the smallest value |
Math.min(5, 10, 15) → 5
|
Custom Clamping |
Restrict a value to a range |
Math.min(Math.max(x, min), max) |
7.其他方法
Method |
Description |
Example |
Math.sign(x) |
Returns 1, -1, or 0 based on sign of x
|
Math.sign(-10) → -1
|
Math.fround(x) |
Nearest 32-bit floating-point number |
Math.fround(5.5) → 5.5
|
Math.clz32(x) |
Counts leading zero bits in 32-bit binary |
Math.clz32(1) → 31
|
範例
1 到 100 之間的隨機整數
const randomInt = Math.floor(Math.random() * 100) + 1;
console.log(randomInt);
登入後複製
計算圓面積
const radius = 5;
const area = Math.PI * Math.pow(radius, 2);
console.log(area); // 78.54
登入後複製
登入後複製
將度數轉換為弧度
const degrees = 90;
const radians = degrees * (Math.PI / 180);
console.log(radians); // 1.57
登入後複製
找出數組中最大的數字
const nums = [5, 3, 9, 1];
console.log(Math.max(...nums)); // 9
登入後複製
數學物件的擴充用例
Math 物件有許多實際應用。以下列出了常見場景和範例,以說明如何有效使用它。
1.隨機化
產生一個範圍內的隨機整數
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
console.log(getRandomInt(1, 10)); // Random number between 1 and 10
登入後複製
打亂數組
function shuffleArray(arr) {
return arr.sort(() => Math.random() - 0.5);
}
console.log(shuffleArray([1, 2, 3, 4, 5])); // Shuffled array
登入後複製
模擬擲骰子
function rollDice() {
return Math.floor(Math.random() * 6) + 1; // Random number between 1 and 6
}
console.log(rollDice());
登入後複製
2.幾何與形狀
計算圓的面積
const radius = 5;
const area = Math.PI * Math.pow(radius, 2);
console.log(area); // 78.54
登入後複製
登入後複製
計算三角形的斜邊
const a = 3, b = 4;
const hypotenuse = Math.hypot(a, b);
console.log(hypotenuse); // 5
登入後複製
將度數轉換為弧度
function degreesToRadians(degrees) {
return degrees * (Math.PI / 180);
}
console.log(degreesToRadians(90)); // 1.57
登入後複製
3.金融與商業
複利公式
function compoundInterest(principal, rate, time, n) {
return principal * Math.pow((1 + rate / n), n * time);
}
console.log(compoundInterest(1000, 0.05, 10, 12)); // 47.01
登入後複製
四捨五入貨幣值
const amount = 19.56789;
const rounded = Math.round(amount * 100) / 100; // Round to 2 decimal places
console.log(rounded); // 19.57
登入後複製
計算折扣
function calculateDiscount(price, discount) {
return Math.floor(price * (1 - discount / 100));
}
console.log(calculateDiscount(200, 15)); // 0
登入後複製
4.遊戲與動畫
模擬投擲硬幣
function coinToss() {
return Math.random() < 0.5 ? 'Heads' : 'Tails';
}
console.log(coinToss());
登入後複製
平滑動畫的緩動函數
function easeOutQuad(t) {
return t * (2 - t); // Simple easing function
}
console.log(easeOutQuad(0.5)); // 0.75
登入後複製
二維網格中的隨機生成座標
function randomCoordinates(gridSize) {
const x = Math.floor(Math.random() * gridSize);
const y = Math.floor(Math.random() * gridSize);
return { x, y };
}
console.log(randomCoordinates(10)); // e.g., {x: 7, y: 2}
登入後複製
5.數據分析
求數組中的最大值和最小值
const scores = [85, 90, 78, 92, 88];
console.log(Math.max(...scores)); // 92
console.log(Math.min(...scores)); // 78
登入後複製
標準化數據
function normalize(value, min, max) {
return (value - min) / (max - min);
}
console.log(normalize(75, 0, 100)); // 0.75
登入後複製
6.物理與工程
計算自由落體後的速度
const gravity = 9.8; // m/s^2
const time = 3; // seconds
const velocity = gravity * time;
console.log(velocity); // 29.4 m/s
登入後複製
鐘擺週期
function pendulumPeriod(length) {
return 2 * Math.PI * Math.sqrt(length / 9.8);
}
console.log(pendulumPeriod(1)); // 2.006 seconds
登入後複製
7.數位操控
將數字限制在某個範圍內
function clamp(value, min, max) {
return Math.min(Math.max(value, min), max);
}
console.log(clamp(15, 10, 20)); // 15
console.log(clamp(5, 10, 20)); // 10
登入後複製
將負數轉換為正數
console.log(Math.abs(-42)); // 42
登入後複製
找出數字的整數部分
console.log(Math.trunc(4.9)); // 4
console.log(Math.trunc(-4.9)); // -4
登入後複製
8.解決問題
檢查數字是否為 2 的冪
function isPowerOfTwo(n) {
return Math.log2(n) % 1 === 0;
}
console.log(isPowerOfTwo(8)); // true
console.log(isPowerOfTwo(10)); // false
登入後複製
產生斐波那契數
function fibonacci(n) {
const phi = (1 + Math.sqrt(5)) / 2;
return Math.round((Math.pow(phi, n) - Math.pow(-phi, -n)) / Math.sqrt(5));
}
console.log(fibonacci(10)); // 55
登入後複製
9.雜項
產生隨機顏色 (RGB)
function getRandomColor() {
const r = Math.floor(Math.random() * 256);
const g = Math.floor(Math.random() * 256);
const b = Math.floor(Math.random() * 256);
return `rgb(${r}, ${g}, ${b})`;
}
console.log(getRandomColor()); // e.g., rgb(123, 45, 67)
登入後複製
根據出生日期計算年齡
function calculateAge(birthYear) {
const currentYear = new Date().getFullYear();
return currentYear - birthYear;
}
console.log(calculateAge(1990)); // e.g., 34
登入後複製
以上是JavaScript 數學物件備忘單的詳細內容。更多資訊請關注PHP中文網其他相關文章!