Để tính gốc cuối của một số, hãy sử dụng phương thức Math.abs (). Ở đây, chúng tôi cũng đang sử dụng phương thức Match.pow. Bạn có thể thử chạy đoạn mã sau để tính căn bậc hai của các số trong JavaScript -
Ví dụ
<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>