javascript - 将函数更改为也适用于负值?
问题描述
我的应用程序中有一个函数,它接受一个值并以一种特殊的方式将其输出。在那里计算一个值是相同的值,但拆分为“小时:分钟”。
我需要该函数也适用于负值 - 类似于函数内部的 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 它解决了我的问题!伟大的帮助家伙 - 有一个美好的一天!
解决方案
您可以在开头添加检查并调用相同的功能更改符号。
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));
推荐阅读
- python - Python - 将单个 csv 单元格拆分为多个单元格
- oracle - 我正在尝试使用 sql developer 删除 Oracle 中的 dbms_jobs。
- javascript - 选中复选框后的新 Dropbox
- php - Woocommerce 购物车刷新
- sql-server - 将 CSV 导入 SQL Server 时无法在输入文件中找到模式
- javascript - 反应:TypeError:无法读取未定义的属性“名称”
- sql-server - 索引优化排除特定表
- coq - 如何将 Coq 的 Z 提取为 Haskell 的整数
- wpf - 通用 ReactiveUserControl“无法在设计视图中编辑”
- javascript - 当页面加载时,给我 url - Firefox 扩展