javascript - Mixed let/const array destructuring from split string
问题描述
TS throws an error:
'parsedHours' is never reassigned. Use 'const' instead prefer-const
'parsedMinutes' is never reassigned. Use 'const' instead prefer-const
When trying to deconstruct this array, after a string split:
let [
parsedHours = '00',
parsedMinutes = '00',
parsedSeconds = '00',
parsedMillis = '000'
] = "12:34:56".split(':');
if (parsedSeconds.includes('.')) {
[parsedSeconds, parsedMillis] = parsedSeconds.split('.');
}
Hours and minutes should be declared as constants, but Seconds and Millis may change, thus should be declared as let. This can be fixed in many approaches, but I can't find a beautiful way of doing this.
Any ideas?
解决方案
You basically have a couple of options:
Turn off the lint rule (I'm 99% sure it's not TypeScript itself saying this, but TSLint or ESLint or similar).
Save the array, then use
const
orlet
as desired.Use
const
for all of them by using a regular expression (perhaps with named capture groups) that handles the possible formats you're feeding it.
Here's #2:
const result = "12:34:56".split(":");
const [parsedHours = "00", parsedMinutes = "00"] = result;
let [, , parsedSeconds = "00", parsedMillis = "000"] = result;
// ...
Here's #3:
const rexTime = /^(?<hours>\d{1,2}):(?<minutes>\d{1,2}):(?<seconds>\d{1,2})(?:\.(?<millis>\d{1,3}))?$/;
function example(timeString) {
const {
groups: {
hours = "00",
minutes = "00",
seconds = "00",
millis = "000"
} = {}
} = rexTime.exec(timeString) ?? {};
console.log(
timeString,
"=>",
hours,
minutes,
seconds,
millis
);
}
example("12:34:56");
example("12:34:56.123");
There are a dozen different ways to spin that, that's just one of them, but it gives you the idea.
推荐阅读
- reactjs - 反应日历库
- javascript - 通过 SharePoint 中的 javascript/SP 服务根据用户组成员身份在列表视图中隐藏项目行(整行)
- swift - watchOS 并发症 - 重新加载超过每日预算?
- rest - 如何使用 InvokeHttp 来休息 Api(POST)
- python - 检查数组的元素是否在边界内
- c# - GestureRecognizer 无法使用 DataTemplate 处理 CollectionView
- python - 我收到此错误:ModuleNotFoundError: No module named 'bs4'
- sql - 在 Django 中,如何根据子查询的子查询获取记录数?
- android - 如何使 AOSP 构建 VNDK 兼容?
- python - Sqlalchemy:检索应用过滤器的相关行