在 JavaScript 中将时间拆分为小时、分钟、秒
要将时间拆分为小时、分钟和秒,请在时间字符串上调用 split()
方法,将分隔符作为参数传递给它,例如 time.split(':')
。 split
方法将返回一个包含 3 个字符串的数组——小时、分钟和秒。
const time = '09:30:46';
const [hours, minutes, seconds] = time.split(':');
console.log(hours); // 👉️ "09"
console.log(minutes); // 👉️ "30"
console.log(seconds); // 👉️ "46"
我们传递给 String.split
方法的唯一参数是分隔符,我们要在其上拆分字符串,在我们的例子中是一个冒号。
const time = '09:30:46';
// 👇️ ['09', '30', '46']
console.log(time.split(':'));
String.split
方法返回一个包含 3 个元素的数组 - 小时、分钟和秒。
我们使用解构赋值将数组中的值赋给小时、分钟和秒变量。
const [a, b, c] = [1, 2, 3];
console.log(a); // 👉️ 1
console.log(b); // 👉️ 2
console.log(c); // 👉️ 3
使用解构赋值时,变量会以相同的顺序从数组中赋值。
最终结果由 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
如何在 JavaScript 中合并两个数组而不出现重复的情况
发布时间:2024/03/23 浏览次数:86 分类:JavaScript
-
本教程介绍了如何在 JavaScript 中合并两个数组,以及如何删除任何重复的数组。