gpt4 book ai didi

Javascript - 从末尾开始移动的子字符串

转载 作者:行者123 更新时间:2023-12-02 23:49:05 25 4
gpt4 key购买 nike

我不确定这是否重复,但我需要将字符串分解为子字符串以将时间分隔符放入其中。我想通过从字符串的长度开始并反向移动 2 个位置,将 2016 变成 20.16,将 21070 变成 2:10.70。

我在 2016 年尝试过以下操作:

best.toString().slice(-2, best.toString().length); //16
best.toString().slice(-2, (best.toString().length - 2)); //blank

我在 21070 上厌倦了以下内容:

best.toString().slice(-2, best.toString().length); //70
best.toString().slice(-2, (best.toString().length - 2)); //blank
best.toString().slice(-2, (best.toString().length - 4)); //blank

切片的起点我缺少什么?谢谢!

最佳答案

你甚至不需要使用切片

function format(best) {
const a = (best / 10000) | 0;
const b = ((best / 100) | 0) % 100;
const c = (best % 100)

let result = '';
if (a > 0) result += a.toString() + ':';
result += b.toString().padStart(2, '0') + '.';
result += c.toString().padStart(2, '0');

return result;
}

format(2016); // 20.16
format(21070); // 2:10.70

关于Javascript - 从末尾开始移动的子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55718929/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com