迹忆客 专注技术分享

当前位置:主页 > 学无止境 > WEB前端 > JavaScript >

在 JavaScript 中将时间拆分为小时、分钟、秒

作者:迹忆客 最近更新:2022/12/18 浏览次数:

要将时间拆分为小时、分钟和秒,请在时间字符串上调用 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"

JavaScript 中将时间拆分为小时、分钟、秒

我们传递给 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 个字符串组成,我们可以根据用例对其进行操作。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

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 POST

发布时间:2024/03/23 浏览次数:96 分类:JavaScript

本教程讲解如何在不使用 JavaScript 表单的情况下发送 POST 数据。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便