JavaScript 中的模数运算符(%)
本教程讲解如何在 JavaScript 中使用模运算符%
。
JavaScript 中的余数运算符%
当一个数字除以另一个数字时,它将给出剩余的余数。该运算符与其他语言中的 modulo
运算符不同,因为它具有不同的用途。它们的结果仅对于正数被除数相同,但是如果我们有负被除数 a
并对其应用模运算符,则结果将完全不同。在 JavaScript 中使用余数运算符通过表达式 ( (a % n) + n) % n
获得的结果与在 a % n
中使用模运算符获得的结果相同。
在 JavaScript 中使用余数运算符%
的示例
被除数为正的余数运算情况
1 % -2 // 1
2 % 3 // 2
5.5 % 2 // 1.5
12 % 5 // 2
1 % 2 // 1
被除数为负的余数运算情况
-12 % 5 // -2
- 1 % 2 // -1
- 4 % 2 // -0
被除数为 NaN
的余数运算情况
NaN % 2 // NaN
被除数为无限的余数运算情况
Infinity % 2 // NaN
Infinity % 0 // NaN
Infinity % Infinity // NaN
应用
数字是奇数还是偶数
我们可以通过检查整数是否可以被 2
整除来检查它是否为偶数。我们可以使用模运算符的返回值。如果为 0
,则表示数字为偶数。
function isEven(n) {
return n % 2 === 0;
}
isEven(6); // true
isEven(3); // false
数字的小数部分
我们可以简单地通过计算 n % 1
来做到这一点。
function getFractionalPart(n) {
return n % 1;
}
getFractionalPart(2.5); // 0.5
将分钟转换为小时
当给定表示分钟数的数字 n
,并且我们想将其转换为小时和分钟时,我们可以使用模运算符。
const minutesToHoursAndMinutes = n =>
({hours: Math.floor(n / 60), minutes: n % 60});
minutesToHoursAndMinutes(123); // { hours: 2, minutes: 3 }
相关文章
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 事件。