JavaScript 布尔函数
与大多数其他编程语言不同,JavaScript 拥有布尔类型作为原始数据类型。 布尔类型大多将 true 和 false 作为唯一的默认值。
但在某些情况下,我们也将 0 表示为 false,将 1 表示为 true。
在下面的示例集中,我们将研究布尔类型的基本驱动和布尔函数的工作原理。 在这里,我们需要知道的一件事是 === 和 == 之间的区别。
当我们提到严格相等运算符===时,它肯定要匹配数据类型以及匹配格式。
假设我们正在使用严格相等运算符比较字符串“123”和数字 123。 这将导致错误值; 或者更简单的话,它不会显示匹配项。
同样,如果我们认为匹配 0 为假,1 为真,我们将不会得到匹配。 让我们检查一下实例以更好地理解。
基本类型的基本使用 - JavaScript 中的布尔值
我们将执行一个简单的数学驱动来得出布尔值。 从技术上讲,任何具有值的变量都将被称为 true。
在这里,我们将检查给定变量除以 2 的余数。如果结果令人满意,我们打印正确的,否则打印错误的。
此外,我们还将了解严格相等运算符如何执行以及通用 == 相等运算符如何工作。
代码片段:
var a = 5;
var x = a%2;
if(x==1){
console.log("correct");
}
else{
console.log("incorrect");
}
if(x===true){
console.log("ok");
}
else{
console.log("not ok");
}
输出:
可以看出,我们在第一个条件语句中得到了条件的真值。 在我们将 1 匹配为 true 的部分中,它没有给出预期的结果。
这定义了严格相等运算符如何防止数据类型不匹配。
JavaScript 中布尔函数的使用
在这种情况下,布尔函数的运算不需要任何条件语句来评估真或假。 基本函数以表达式为参数得出答案。
这里的输出总是 true 或 false。 让我们检查一下代码行。
代码片段:
var a = 5;
var b = 4;
var x = a%2;
var y = b%2;
console.log(Boolean(x))
console.log(Boolean(y))
输出:
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
用 jQuery 检查复选框是否被选中
发布时间:2024/03/24 浏览次数:102 分类:JavaScript
-
在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的
jQuery 中的 Window.onload 与 $(document).ready
发布时间:2024/03/24 浏览次数:180 分类:JavaScript
-
本教程演示了如何在 jQuery 中使用 Window.onload 和 $(document).ready 事件。