Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Short-circuit evaluation trong JavaScript

Short circuit evaluation cơ bản hoạt động với các toán tử logic && và ||. Các biểu thức được đánh giá từ trái sang phải.

Với toán tử && - Short circuit evaluation với &&(AND) có nghĩa là nếu biểu thức đầu tiên đánh giá thành false thì toàn bộ biểu thức sẽ là false và các biểu thức còn lại sẽ không được đánh giá.

Với toán tử || - Short circuit evaluation với ||(OR) có nghĩa là nếu biểu thức đầu tiên đánh giá thành true thì toàn bộ biểu thức sẽ là true và các biểu thức còn lại sẽ không được đánh giá.

Dưới đây là mã về short circuit evaluation 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;    }    .result {       font-size: 20px;       font-weight: 500;       color: blueviolet;    } </style> </head> <body> <h1>Short-circuit evaluation</h1> <div class="result"></div> <br /> <button class="Btn">&& short circuit evaluation</button> <button class="Btn">|| short circuit evaluation</button> <h3>Nhấn nút trên để xem short circuit evaluation</h3> <script>    let resEle = document.querySelector(".result");    let BtnEle = document.querySelectorAll(".Btn");    function retTrue() {       resEle.innerHTML += "True <br>";       return true;    }    function retFalse() {       resEle.innerHTML += "False <br>";       return false;    }    BtnEle[0].addEventListener("click", () => {       resEle.innerHTML = "&& evaluation<br>";       retFalse() && retTrue();    });    BtnEle[1].addEventListener("click", () => {       resEle.innerHTML = "|| evaluation <br>";       retTrue() || retFalse();    }); </script> </body> </html>

Kết quả

Short-circuit evaluation trong JavaScript

Khi nhấn nút "&& short circuit evaluation":

Short-circuit evaluation trong JavaScript

Khi nhấn nút '|| short circuit evaluation':

Short-circuit evaluation trong JavaScript