鉴于这些输入:开始,结束,凹槽数量
start = a number;
end = a larger number;
numberOfNotches = a number; // includes start and end values
如何计算显示范围的中间值?
例如:
start = 100;
end = 200;
numberOfNotches = 6; // includes start and end values
输出:
100 ----- 120 ----- 140 ----- 160 ----- 180 ----- 200
以下是我目前在JavaScript中的内容
function getNotchValues(from, to, numberOfNotches){
var step = Math.floor( ( (to - from) / (numberOfNotches-2) ));
from = Math.floor(from/step)*step;
to = Math.ceil(to/step)*step;
var arr = [];
for(var i=from; i<=to; i=i+step){
arr.push(i);
}
return arr;
}
这是我迄今为止的逻辑,但它对我不起作用:http://jsfiddle.net/w8vwG/
答案 0 :(得分:1)
看起来像off-by-one/fencepost问题。似乎可以通过一个小改动来正常工作:
(numberOfNotches-1)
在这一行:
var step = Math.floor( ( (to - from) / (numberOfNotches-1) ));
编辑:
我认为这是一个完整的解决方案,在下面的评论中处理这个问题:
function getNotchValues(from, to, numberOfNotches) {
var step = Math.floor(((to - from) / (numberOfNotches - 1)));
var arr = [];
for (var i = from; i <= to; i = i + step) {
arr.push(i);
}
arr[arr.length - 1] = to
return arr;
}