我有一个函数,它会通过点击按钮从timer的currentTime产生数组值。在这种情况下,结果如下:
var data_catch = ["0", "24.871604", "27.1788", "29.69", "29.100", "30.570661"];
然后我需要在数组值与规则之间获得持续时间"下一个值将减少之前的值"这让我用这种方式:
var data_duration = [];
for (var i = 1; i < data_catch.length; i++) {
data_duration.push(data_catch[i]-data_catch[i-1]);
}
console.log(data_duration);
data_duration
的值永远不应该是负数,因为定时器总是在前进,而currentTime总是比前一个currentTime有更大的值。但在这种情况下,data_duration的结果是:
data_duration = [
24.871604,
2.3071959999999976,
2.5112000000000023,
-0.5899999999999999,
1.4706609999999998
];
由于此减少,结果只有一个减值29.100 - 29.69
为什么会这样,以及如何解决这个问题?请帮帮我..
答案 0 :(得分:2)
您可以使用Math.abs获取绝对值。在数学上29.69
大于29.100
var data_catch = ["0", "24.871604", "27.1788", "29.69", "29.100", "30.570661"];
var data_duration = [];
for (var i = 1; i < data_catch.length; i++) {
data_duration.push(Math.abs(data_catch[i] - data_catch[i - 1]));
}
console.log(data_duration);