在 JavaScript 中将秒转换为分钟
我们将考虑一种应用数学表达式将秒转换为分钟的基本方法。
在我们的驱动器中,我们最初将给定值(以秒为单位)除以 60
作为 1 分钟 = 60 秒
。有了这个基本概念,我们将检索指定秒的相应分钟。
在这里,具体来说,我们将看到一个初等数学的例子。另一个将以美化格式输出,我们将使用 toString()
方法和 padStart()
方法。
让我们跳到代码以更好地预览解决方案。
JavaScript 中秒到分钟的基本转换
我们将设置一个合适的数字(考虑以秒为单位的值)。我们将这个数字除以 60
并将 floor
值作为整数分钟值。
为了计算不能放入整分钟的剩余秒数,我们将对整个 second
数字 (var = time_s
) 执行 mod
通过 60
。因此,通过将 time_s
除以 60
,我们将得到完整的分钟数,余数将通过 time_s mod(%) 60
来计算。
代码片段:
var time_s = 462;
var minute = Math.floor(time_s / 60);
var rest_seconds = time_s % 60;
console.log(minute + ' minutes ' + rest_seconds + ' seconds.')
输出:
我们有 462 秒,然后除以 60
。执行此表达式后,我们收到值 7.7
并选择 floor
值 7
。
这里的余数是 42
,这是不能达到整分钟的剩余秒数。所以,最后,输出是 7 分 42 秒
。
在 JavaScript 中使用 toString()
和 padStart()
方法格式化 MM:SS
padStart()
方法适用于字符串,因此我们将通过 toString()
方法将我们的数字元素转换为字符串。我们有类似的数学表达式将秒转换为分钟。
但更具体地说,如果我们转换单值分钟或秒,padStart()
方法将使其成为一个 2 位字符串,起始数字为 0
。让我们可视化代码行和输出。
代码片段:
var time_s = 462;
var minute = Math.floor(time_s / 60);
var rest_seconds = time_s % 60;
console.log(
minute.toString().padStart(2, '0') + ':' +
rest_seconds.toString().padStart(2, '0'));
输出:
相关文章
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 事件。