你可以计算出
number
被
100
整除的次数,然后以编程方式创建一个具有该长度的数组。
var number = 525;
var array = new Array(Math.floor(number / 100)).fill(100).concat(number % 100))
// [ 100, 100, 100, 100, 100, 25 ]
您可以将此扩展到任何数量的块:
function chunkBy(number, n) {
var chunks = Array(Math.floor(number / n)).fill(n);
var remainder = number % n;
if (remainder > 0) {
chunks.append(remainder);
}
return chunks;
}
或者,在执行减法之前,可以简单地将该元素推出:
var number = 525;
var array = [];
while (number > 0) {
array.push(Math.min(number, 100));
number = number - 100;
}
使用 ES6 箭头函数:
const chunkBy = (n) => number => {
var chunks = new Array(Math.floor(number / n)).fill(n);
var remainder = number % n;
console.log('CHUNKS = ', chunks);
if (remainder > 0) {
chunks.push(remainder);
}
return chunks;
};
const chunkBy50 = chunkBy(50);
const chunkBy100 = chunkBy(100);
const chunkBy77 = chunkBy(77);
console.log(chunkBy50(500));
console.log(chunkBy100(500));
console.log(chunkBy77(500));