Math.sqrt()
Math.sqrt() 靜態方法返回數字的平方根。即
試一試
function calcHypotenuse(a, b) {
return Math.sqrt(a * a + b * b);
}
console.log(calcHypotenuse(3, 4));
// Expected output: 5
console.log(calcHypotenuse(5, 12));
// Expected output: 13
console.log(calcHypotenuse(0, 0));
// Expected output: 0
語法
js
Math.sqrt(x)
引數
x-
大於或等於 0 的數字。
返回值
x 的平方根,一個非負數。如果 x < 0,則返回 NaN。
描述
因為 sqrt() 是 Math 的靜態方法,所以你總是使用 Math.sqrt() 來呼叫它,而不是作為你建立的 Math 物件的某個方法(Math 不是一個建構函式)。
示例
使用 Math.sqrt()
js
Math.sqrt(-1); // NaN
Math.sqrt(-0); // -0
Math.sqrt(0); // 0
Math.sqrt(1); // 1
Math.sqrt(2); // 1.414213562373095
Math.sqrt(9); // 3
Math.sqrt(Infinity); // Infinity
規範
| 規範 |
|---|
| ECMAScript® 2026 語言規範 # sec-math.sqrt |
瀏覽器相容性
載入中…