JavaScript – Math對象
JavaScript 中的 Math
對象是用于執行數學任務的內置對象。愛掏網 - it200.com它不需要創建實例就可以使用,但作為一個對象,它擁有一些方法和屬性。愛掏網 - it200.com
Math.PI
Math.PI
屬性返回圓周率的值。愛掏網 - it200.com
console.log(Math.PI); // 3.141592653589793
Math.E
Math.E
屬性返回自然對數的底數。愛掏網 - it200.com
console.log(Math.E); // 2.718281828459045
Math.LN2
Math.LN2
屬性返回 2 的自然對數。愛掏網 - it200.com
console.log(Math.LN2); // 0.6931471805599453
Math.LN10
Math.LN10
屬性返回 10 的自然對數。愛掏網 - it200.com
console.log(Math.LN10); // 2.302585092994046
Math.LOG2E
Math.LOG2E
屬性返回以 2 為底數的自然對數 e 的值。愛掏網 - it200.com
console.log(Math.LOG2E); // 1.4426950408889634
Math.LOG10E
Math.LOG10E
屬性返回以 10 為底數的自然對數 e 的值。愛掏網 - it200.com
console.log(Math.LOG10E); // 0.4342944819032518
方法
Math.abs(x)
Math.abs(x)
方法返回 x
的絕對值。愛掏網 - it200.com
console.log(Math.abs(-5)); // 5
console.log(Math.abs(3.14)); // 3.14
Math.ceil(x)
Math.ceil(x)
方法返回大于或等于 x
的最小整數。愛掏網 - it200.com
console.log(Math.ceil(2.1)); // 3
console.log(Math.ceil(-2.1)); // -2
Math.floor(x)
Math.floor(x)
方法返回小于或等于 x
的最大整數。愛掏網 - it200.com
console.log(Math.floor(2.9)); // 2
console.log(Math.floor(-2.9)); // -3
Math.max(x,y,z,…)
Math.max(x,y,z,...)
方法返回數值參數中的最大值。愛掏網 - it200.com
console.log(Math.max(1,2,3)); // 3
console.log(Math.max(-1,-2,-3)); // -1
Math.min(x,y,z,…)
Math.min(x,y,z,...)
方法返回數值參數中的最小值。愛掏網 - it200.com
console.log(Math.min(1,2,3)); // 1
console.log(Math.min(-1,-2,-3)); // -3
Math.pow(x,y)
Math.pow(x,y)
方法返回 x
的 y
次冪。愛掏網 - it200.com
console.log(Math.pow(2,3)); // 8
console.log(Math.pow(4,-1)); // 0.25
Math.round(x)
Math.round(x)
方法返回最接近 x
的整數。愛掏網 - it200.com
console.log(Math.round(3.5)); // 4
console.log(Math.round(3.4)); // 3
Math.sqrt(x)
Math.sqrt(x)
方法返回 x
的平方根。愛掏網 - it200.com
console.log(Math.sqrt(16)); // 4
console.log(Math.sqrt(2)); // 1.4142135623730951
Math.random()
Math.random()
方法返回一個介于 0 到 1 之間的隨機數。愛掏網 - it200.com
console.log(Math.random()); // 0.872493830175382
結論
Math
對象在 JavaScript 中是執行數學任務的重要工具,它擁有許多方法和屬性用于處理數字。愛掏網 - it200.com熟練掌握這些方法和屬性可以在開發中輕松實現數值計算。愛掏網 - it200.com