ในการคำนวณรูทสิ้นสุดของตัวเลข ให้ใช้เมธอด Math.abs() ที่นี่เราใช้วิธี Match.pow ด้วย คุณสามารถลองเรียกใช้รหัสต่อไปนี้เพื่อคำนวณรากที่สองของตัวเลขใน JavaScript -
ตัวอย่าง
<html>
<head>
<title>Calculate root</title>
</head>
<body>
<script>
function displayRoot(x, num) {
val = num % 2;
if((val == 1) || x < 0)
x = -x;
var a, num;
a = Math.pow(x, 1 / num);
num = Math.pow(a, num);
if(Math.abs(x - num) < 1 && (x > 0 === num > 0))
return val ? -a : a;
}
document.write(displayRoot(36, 2));
document.write("<br>"+displayRoot(49, 2));
document.write("<br>"+displayRoot(36, -2));
document.write("<br>"+displayRoot(216, -2));
</script>
-+
</body>
</html>