Math.sqrt() 回傳一個數字的平方根。若傳入負數,結果會是 NaN。
Math.sqrt(x);
x 的平方根;x 為負數時回傳 NaN。
<html>
<head>
<title>JavaScript Math sqrt() Method</title>
</head>
<body>
<script type="text/javascript">
var value = Math.sqrt(0.5);
document.write("First Test Value : " + value);
var value = Math.sqrt(81);
document.write("<br />Second Test Value : " + value);
var value = Math.sqrt(13);
document.write("<br />Third Test Value : " + value);
var value = Math.sqrt(-4);
document.write("<br />Fourth Test Value : " + value);
</script>
</body>
</html>
First Test Value : 0.7071067811865476
Second Test Value : 9
Third Test Value : 3.605551275463989
Fourth Test Value : NaN
NaN 而非拋出例外,所以不會中斷程式,但也容易被忽略。若輸入來源不明,建議先檢查 x >= 0 或用 Number.isNaN() 驗證結果。如果只是想開任意次方根,可以用 Math.pow(x, 1 / n),例如立方根寫成 Math.pow(8, 1 / 3);ES2015 之後也有專用的 Math.cbrt() 可直接計算立方根,並支援負數。