Computer >> Máy Tính >  >> Lập trình >> Javascript

Giải thích toán tử Nhóm trong JavaScript.


Toán tử nhóm được sử dụng để quản lý mức độ ưu tiên của đánh giá biểu thức.

Sau đây là mã cho toán tử nhóm trong JavaScript -

Ví dụ

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .sample,.result {
      font-size: 18px;
      font-weight: 500;
      color: red;
   }
   .result {
      color: rebeccapurple;
   }
</style>
</head>
<body>
<h1>Grouping operator in JavaScript</h1>
<div class="sample">2+2*5/22</div>
<div class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to use group operator to specify precedence</h3>
<script>
   let sampleEle = document.querySelector(".sample");
   let resultEle = document.querySelector(".result");
   document.querySelector(".Btn").addEventListener("click", () => {
      resultEle.innerHTML += "2+2*5/22 = " + (2 + (2 * 5) / 22) + "<br>";
      resultEle.innerHTML += "(2+2)*5/22 = " + ((2 + 2) * 5) / 22 + "<br>";
      resultEle.innerHTML += "(2+2*5)/22 = " + (2 + 2 * 5) / 22 + "<br>";
   });
</script>
</body>
</html>

Đầu ra

Đoạn mã trên sẽ tạo ra kết quả sau -

Giải thích toán tử Nhóm trong JavaScript.

Khi nhấp vào nút 'BẤM VÀO ĐÂY' -

Giải thích toán tử Nhóm trong JavaScript.