Math.sqrt()

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

Phương thức tĩnh Math.sqrt() trả về căn bậc hai của một số. Cụ thể:

x0,𝙼𝚊𝚝𝚑.𝚜𝚚𝚛𝚝(𝚡)=x=the unique y0 such that y2=x\forall x \geq 0,\;\mathtt{\operatorname{Math.sqrt}(x)} = \sqrt{x} = \text{the unique } y \geq 0 \text{ such that } y^2 = x

Try it

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

Cú pháp

js
Math.sqrt(x)

Tham số

x

Một số lớn hơn hoặc bằng 0.

Giá trị trả về

Căn bậc hai của x, là số không âm. Nếu x < 0, trả về NaN.

Mô tả

sqrt() là một phương thức tĩnh của Math, bạn luôn sử dụng nó dưới dạng Math.sqrt(), thay vì là phương thức của một đối tượng Math bạn tạo ra (Math không phải là constructor).

Ví dụ

Sử dụng 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

Đặc tả kỹ thuật

Specification
ECMAScript® 2027 Language Specification
# sec-math.sqrt

Tương thích trình duyệt

Xem thêm