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 |
浏览器兼容性
加载中…