指定要显示的数量。
E.g。如果 如果指定2,则结果应为0和100.如果指定3,则数字应为0,50和100.如果指定4,则数字应为0,33,67,100等。
每个显示的数字之间应始终保持相同的长度。
答案 0 :(得分:2)
for-loop解决方案:
const run = (max, num) => {
let result = [];
let part = max / (num - 1);
for(let i = 0; i < max; i += part) {
result.push(Math.round(i));
}
result.push(max);
return (result);
};
console.log(run(100, 4)); // [0, 33, 67, 100]
console.log(run(100, 5)); // [0, 25, 50, 75, 100]
console.log(run(100, 7)); // [0, 17, 33, 50, 67, 83, 100]
答案 1 :(得分:1)
如果你可以使用es6,这是一个很好的功能性单行:
const fn = (n, l) => [...Array(n)].map((i, id) => Math.floor(l/(n-1) * id))
console.log(fn(4,100))
console.log(fn(2,100))
当你想要整数时,你当然不能总是得到数字之间的确切距离 - 当数字不均匀分开时你需要在某个地方进行舍入。
答案 2 :(得分:0)
function numbers(number){
var max=100;
spacing = Math.floor( max/ (number-1) );
var returnMe = [0];
var cur=spacing;
while(cur <= max){
returnMe.push( cur );
cur+=spacing;
}
return returnMe;
}