我正在尝试找到解决问题的简便方法。
我想尝试并简化它,但是我不知道从哪里开始。
let days = Math.floor(distance / (1000 * 60 * 60 * 24));
if(days > 0) {
days = days + "d";
}
我当时想我可以使用三元运算符来返回计算+“ d”,如下所示:
let days = Math.floor(distance / (1000 * 60 * 60 * 24)) === 0 ? Math.floor(distance / (1000 * 60 * 60 * 24)) + "d" : "";
但是,我认为这很混乱,我想不出另一种方法。
我目前正在为这样的计时器计算天,小时,分钟和秒:
let distance = expiry - now;
let days = Math.floor(distance / (1000 * 60 * 60 * 24));
let hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
let minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
let seconds = Math.floor((distance % (1000 * 60)) / 1000);
此后,我只想显示greater than 0
的天数或greater than 0
的分钟数,依此类推。我目前正在使用一堆if语句和一个布尔值来检查是否已经找到大于0的值。像这样:
let isSet = false;
if (days > 0 && !isSet) {
current = days + "d";
isSet = true;
}
if (hours > 0 && !isSet) {
current = hours + "h";
isSet = true;
}
if (minutes > 0 && !isSet) {
current = minutes + "m";
isSet = true;
}
if (seconds > 0 && !isSet) {
current = seconds + "s";
isSet = true;
}
if (seconds < 0 && !isSet) {
current = "expired";
isSet = true;
}
但是,这确实是非常重复和错误的(即使可行)。
答案 0 :(得分:5)
我认为这种模式的最佳解决方案是在数组中定义范围,然后与之进行比较,以避免代码重复。
var ranges = [
[86400000, 'd'],
[3600000, 'h'],
[60000, 'm'],
[1000, 's'],
]
然后循环遍历此数组,并检查提供的值是否大于当前时间段。
function humanDiff(milliseconds) {
for (var i = 0; i < ranges.length; i++) {
if (milliseconds >= ranges[i][0]) {
return Math.round((milliseconds / ranges[i][0])) + ranges[i][1]
};
}
return milliseconds;
}
var expiry = new Date('2019-03-26 08:29');
var now = new Date('2019-03-26 05:00');
humanDiff(expiry - now) // 3h
答案 1 :(得分:1)
与其将信息存储为变量,还可以将其存储为对象的属性。然后,您可以遍历每个属性,并只设置所需的文本。
const dateInfo = {
days: 1E3 * 60 * 60 * 24,
hours: 1E3 * 60 * 60,
minutes: 1E3 * 60,
seconds: 1E3
};
function check(distance) {
return Object.keys(dateInfo).reduce(function(result, key) {
result[key] = Math.floor(distance / dateInfo[key]);
distance -= dateInfo[key] * result[key];
result[key] = result[key] > 0 ? `${result[key]}${key}` : "";
return result;
}, {});
}
let result = check(1E9);
console.log(result); // result
console.log(Object.values(result).join(" ")); // Print all properties
console.log(Object.values(result).find(item => item) || "Expired"); // Print first property
最有效,最紧凑的方法是:
const dateInfo = {
d: 1E3 * 60 * 60 * 24,
h: 1E3 * 60 * 60,
m: 1E3 * 60,
s: 1E3
};
function check(distance) {
// Find the biggest proprty that is still smaller than the total difference
var key = Object.keys(dateInfo).find(key => dateInfo[key] <= distance);
// No need for % since distance > dateInfo[key]
return `${Math.floor(distance / dateInfo[key]) || "expired"}${key || ""}`;
}
console.log(check(3E9)); //34d
console.log(check(3E7)); //8h
console.log(check(3E5)); //5m
console.log(check(3E3)); //3s
console.log(check(3E0)); //expired
答案 2 :(得分:0)
您可以使用conditional spread
const now = new Date(2018, 1, 5, 10, 11);
const expiry = new Date(2018, 2, 5, 5, 6);
let distance = expiry - now;
let days = Math.floor(distance / (1000 * 60 * 60 * 24));
let hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
let minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
let seconds = Math.floor((distance % (1000 * 60)) / 1000);
const arr = [
...(days > 0 ? [days + "d"] : []),
...(hours > 0 ? [hours + "h"] : []),
...(minutes > 0 ? [minutes + "m"] : []),
...(seconds > 0 ? [seconds + "s"] : []),
];
const current = arr.length ? arr.join(' ') : "expired";
console.log(current);
答案 3 :(得分:0)
您最大的问题是isSet
变量,而不是您使用的是if
语句。
您应该使用isSet
:而不是设置else
:
var current;
if (days > 0) {
current = days + "d";
} else if (hours > 0) {
current = hours + "h";
} else if (minutes > 0) {
current = minutes + "m";
} else if (seconds > 0) {
current = seconds + "s";
} else if (seconds < 0) {
current = "expired";
} // else seconds == 0
您可能要在此处使用条件运算符。您不应尝试将它们合并到days = Math.floor(distance / (1000 * 60 * 60 * 24))
计算中,而应保留原样-days
只是一个临时变量。将条件的结果存储在其他变量(current
)中,而不是存储在days
中:
const distance = expiry - now;
const days = Math.floor(distance / (1000 * 60 * 60 * 24));
const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
const seconds = Math.floor((distance % (1000 * 60)) / 1000);
const current =
(days > 0) ? days + "d" :
(hours > 0) ? hours + "h" :
(minutes > 0) ? minutes + "m" :
(seconds > 0) ? seconds + "s" :
//(seconds == 0) ? undefined :
"expired";
答案 4 :(得分:0)
getDurationDetails:function(duration){
var result = [];
var units = {
Year:31536000,
Month:2592000,
Week:604800,
Day: 86400,
Hour: 3600,
Minute: 60,
Second:1,
};
for(var name in units) {
var res = Math.floor(duration/units[name]);
if(res == 1) result.push(" " + res + " " + name);
if(res >= 2) result.push(" " + res + " " + name + "s");
duration %= units[name];
}
return result;
},
尝试这个
答案 5 :(得分:0)
您可以采用值的数组,如果找到索引,则以该索引作为值和后缀的访问者,或者以'expired'
作为值。
let distance = expiry - now,
factors = [86400000, 3600000, 60000, 1000],
values = factors.map(f => [Math.floor(distance / f), distance %= f][0]),
index = values.findIndex(v => v > 0),
result = index === -1 ? 'expired' : value[index] + 'DHMS'[index];
console.log(result);
答案 6 :(得分:0)
像您这样的瀑布方法也不错。添加到字符串时,我将对其进行修改以更新距离变量(例如4d 3h 17m 1s
)
function formatDuration (seconds) {
let s = seconds, r = '', t;
if (s % 86400 !== s) updateR('d', 86400);
if (s % 3600 !== s) updateR('h', 3600);
if (s % 60 !== s) updateR('m', 60);
if (s > 0) updateR('s', 1);
function updateR(unit, n) {
t = Math.floor(s / n);
s %= n;
r += (r === '' ? '' : ' ') + t + unit;
}
return r.replace(/,\s(?=\d{1,2}\s\w+$)/, ' and ') || 'expired';
}
以及更具表现力的版本(例如4 days, 3 hours, 17 minutes, and 1 second
):
function formatDuration (seconds) {
let s = seconds, r = '', t;
// if (s % 31536000 !== s) updateR(' year', 31536000);
if (s % 86400 !== s) updateR(' day', 86400);
if (s % 3600 !== s) updateR(' hour', 3600);
if (s % 60 !== s) updateR(' minute', 60);
if (s > 0) updateR(' second', 1);
function updateR(unit, n) {
t = Math.floor(s / n);
s %= n;
r += (r === '' ? '' : ', ') + t + unit + (t === 1 ? '' : 's');
}
return r.replace(/,\s(?=\d{1,2}\s\w+$)/, ' and ') || 'expired';
}