首页 > 解决方案 > 将函数更改为也适用于负值?

问题描述

我的应用程序中有一个函数,它接受一个值并以一种特殊的方式将其输出。在那里计算一个值是相同的值,但拆分为“小时:分钟”。

我需要该函数也适用于负值 - 类似于函数内部的 if 检查以检查输入的时间是否为负,然后更改计算/输出。

这是非常简单的功能:

   const calcSingle = time => {        
      // insert a if check somewhere here to check for time and if its negative
      let hour = Math.floor(time / 60);
      let minutes = time % 60;

      hour = hour < 10 ? "0" + hour : hour;
      minutes = minutes < 10 ? "0" + minutes : minutes;

      return hour + ":" + minutes;
  };

例如,如果我调用它:

calcSingle(200)我得到正确的值“03:20”。

但是,如果我尝试calcSingle(-200)得到:“0-4:0-20”,这显然是错误的,因为它应该是相同的值但带有一个减号,所以这 =>“-03:20”。

const calcSingle = time => {
  // insert a if check somewhere here to check for time and if its negative
  let hour = Math.floor(time / 60);
  let minutes = time % 60;

  hour = hour < 10 ? "0" + hour : hour;
  minutes = minutes < 10 ? "0" + minutes : minutes;

  return hour + ":" + minutes;
};
console.log(
  calcSingle(200)
)


console.log(
  calcSingle(-200)
)

编辑:感谢你们所有人的所有回复,我将使用 math.abs 它解决了我的问题!伟大的帮助家伙 - 有一个美好的一天!

标签: javascriptreactjsreact-nativemathtime

解决方案


您可以在开头添加检查并调用相同的功能更改符号。

  if (time < 0) {
    return `-${calcSingle(Math.abs(time))}`;
  }

像这样

const calcSingle = time => {
  if (time < 0) {
    return `-${calcSingle(Math.abs(time))}`;
  }

  // insert a if check somewhere here to check for time and if its negative
  let hour = Math.floor(time / 60);
  let minutes = time % 60;

  hour = hour < 10 ? "0" + hour : hour;
  minutes = minutes < 10 ? "0" + minutes : minutes;

  return hour + ":" + minutes;
};

console.log(calcSingle(200));
console.log(calcSingle(-200));


推荐阅读