是否可以在不重复所述值的情况下从三元运算中返回比较值+一个字符串?

问题描述 投票:4回答:7

我正试图找到一个更容易解决问题的方法。

问题:

我想尝试并简化这个,但我不知道从哪里开始。

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;
}

然而,这确实感觉非常重复和错误(即使它有效)。

javascript if-statement ternary-operator
7个回答
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
投票

您可以将它们存储为对象的属性,而不是将信息存储为变量。然后,您可以遍历每个属性,只需设置所需的文本即可。

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

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);

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;
        },

试试这个


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";

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';
}

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);
© www.soinside.com 2019 - 2024. All rights reserved.