问题描述
有没有一种方法可以舍入不同的值,使其具有相同的“距离”? 例如,我有这个值:
100
105.3
110.7
115.1
当我使用Math.round()时,数字之间的距离是不同的:
100
105 // distance is 5 to the previous value
111 // distance is 6 to the previous value
115 // distance is 4 to the previous value
当然,我可以使用Math.floor()或Math.ceil(),但问题是在运行时值将不同,并且所有数字的距离永远都不会相同。
我需要SVG对象:
line.setAttribute('x1', Math.round(x1)); // x1 will have values like 85, 130.3, 175.6, 220.89999999999998 for example
1楼
vapurrmaid
1
2019-03-02 20:42:53
如果您仅考虑先前的值,则可以定义一个curried函数用于您感兴趣的距离。
以下是使用距离5
的演示。
使用map
,您可以在数据数组上运行此命令,以将每个条目强制与上一个条目定义的距离。
编辑
向函数添加了Math.round()
,尽管您也可以在函数的返回值上使用它。
const previousDistance = (distance) => (previous, current) => { if (current > previous) { return Math.round((current - previous > distance) ? previous + distance : current); } else { return Math.round((previous - current > distance) ? previous - distance : current); } } const previousDistanceFive = previousDistance(5); // outside distance (below) console.log(previousDistanceFive(5, -1)); // -> 0 // inside distance (below) console.log(previousDistanceFive(5, 1.1)); // -> 1 // equal console.log(previousDistanceFive(5, 5)); // -> 5 // inside distance (above) console.log(previousDistanceFive(5, 9.123)); // -> 9 // outside distance (above) console.log(previousDistanceFive(5, 11)); // - > 10 // --- DEMONSTRATION ON Array const arr = [0, 5, 7, 16, 17, 10, 16]; // -> [0, 5, 7, 12, 17, 12, 15] const roundedArr = arr.map((elem, i) => { if (i > 0) { return previousDistanceFive(arr[i - 1], elem); } else { return elem; } }); console.log("Array Demo: ", roundedArr);