您好,我有一个函数,它旨在根据我正在调用的 API 构建部分 ISO 时间戳,它应该返回的时间戳示例:
2017Z
2017-12Z
2017-12-24Z
2017-12-24T14Z
2017-12-24T14:07Z
我用来执行此操作的代码如下:
function parsePartialDateTime(datetime = {}) {
if (datetime === null || datetime.year === undefined) {
return null;
}
let dateString = `${datetime.year}`;
if (datetime.month) {
dateString += `-${datetime.month}`;
if (datetime.day) {
dateString += `-${datetime.day}`;
if (datetime.hour) {
dateString += `T${datetime.hour}`;
if (datetime.minute) {
dateString += `:${datetime.minute}`;
if (datetime.second) {
dateString += `:${datetime.second}`;
}
}
}
}
}
return `${dateString}Z`;
}
我真的不确定如何消除对嵌套 if 函数的需求,因为它应该只构建时间戳的每个元素,前提是前面的项目存在(它们都在 datetime 对象中作为字符串/数字提供。
如有任何帮助,我们将不胜感激:)
最佳答案
您可以将值放在一个数组中并循环遍历它们:
// Just for brevity in this example
var dt = datetime;
// Put all the units you want checked in this array
var units = [dt.month, dt.day, dt.hour, dt.minute, dt.second];
var dateString = dt.year
// Then loop over the array...
for (let unit of units) {
//... checking and adding like you were before
if (unit) {
dateString += `-${unit}`;
} else {
// So the rest of the object gets ignored
break;
}
}
正如评论中所指出的,这对每个 unit
使用了相同的分隔符。它增加了少量的复杂性来解决这个问题:
// Each unit is paired with the delimiter that should be used on its left
var units = [[dt.month, "-"], [dt.day, "-"], [dt.hour, "T"],
[dt.minute, ":"], [dt.second, ":"]];
var dateString = dt.year
// Deconstruct out the unit and the delimiter
for (let [unit, delim] of units) {
if (unit) {
dateString += delim + `${unit}`;
} else {
break;
}
}
由于代码中的每个分支基本上都采用 if (x) y += x
的形式,因此可以很容易地提取出来。如果您一遍又一遍地做几乎相同的事情,请尝试做一个循环。
关于javascript - 如何降低此 javascript 时间戳生成器函数的复杂性/嵌套 ifs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47961316/