JavaScript 中的嚴格相等 vs 寬鬆相等。
寬鬆相等運算子 ‘==’ 允許我們先將兩個或更多運算元的值轉換為一種常見型別,然後檢查它們之間的相等性來進行比較。
嚴格相等運算子 ‘===’ 允許我們透過檢查值和型別之間的相等性來比較兩個或更多運算元。它僅在值和型別都與另一個運算元匹配時才返回 true。
以下是 JavaScript 中寬鬆相等與嚴格相等的程式碼−
示例
<!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>Strict equality vs Loose equality</h1>
<div class="result"></div>
<br />
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button see some comparisons using loose equality and strict equality</h3>
<script>
let resEle = document.querySelector(".result");
let BtnEle = document.querySelector(".Btn");
BtnEle.addEventListener("click", () => {
resEle.innerHTML = "According to loose equality <br>";
if (1 == "1") {
resEle.innerHTML += "1 is equal to '1'<br>";
}
if (undefined == null) {
resEle.innerHTML += "undefined is equal to null <br>";
}
resEle.innerHTML += "<br>According to strict equality <br>";
if (1 === "1") {
resEle.innerHTML += "1 is equal to '1'<br>";
} else {
resEle.innerHTML += "1 is not equal to '1'<br>";
}
if (undefined === null) {
resEle.innerHTML += "undefined is equal to null <br>";
} else {
resEle.innerHTML += "undefined is not equal to null <br>";
}
});
</script>
</body>
</html>輸出

單擊‘單擊此處’按鈕後 −

廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP