如何在JavaScript中均匀分布数组元素并用指定值填充空位?
问题描述
输入三个参数:
- 原数组
input_array - 总长度整数
total_count(保证原数组长度 ≤ total_count) - 填充值
fill_value
需要生成一个长度为 total_count 的数组,规则是将原数组元素按顺序插入,剩余位置用 fill_value 填充,填充值尽可能均匀分布在原元素之间(包括最后一个元素之后)。
示例输入:
input_array = ['hello', 'there', 'world'] total_count = 15 fill_value = null
期望输出:
output = [ 'hello', null, null, null, null, 'there', null, null, null, null, 'world', null, null, null, null, ]
其他场景:
- 当
total_count = 3,输出['hello', 'there', 'world'] - 当
total_count = 4,输出['hello', null, 'there', 'world']
解决方案
不需要递归,通过简单的数值计算和数组遍历就能实现,核心是先分配基础填充量,再处理剩余填充值的分配:
步骤分析
- 计算总填充量:
fillTotal = total_count - input_array.length - 计算每个原元素的基础填充数:
baseFill = Math.floor(fillTotal / input_array.length) - 计算需要多填充1个值的元素数量:
extraFillCount = fillTotal % input_array.length - 遍历原数组,对每个元素:
- 先将当前元素加入结果数组
- 再添加
baseFill + (当前元素索引 < extraFillCount ? 1 : 0)个填充值
- 最后截取结果数组到
total_count长度(做兜底处理)
代码实现(JavaScript)
function buildFilledArray(input_array, total_count, fill_value) { const result = []; const fillTotal = total_count - input_array.length; const baseFill = Math.floor(fillTotal / input_array.length); const extraFillCount = fillTotal % input_array.length; input_array.forEach((item, index) => { result.push(item); // 计算当前元素需要携带的填充数 const currentFillCount = baseFill + (index < extraFillCount ? 1 : 0); // 批量添加填充值 for (let i = 0; i < currentFillCount; i++) { result.push(fill_value); } }); return result.slice(0, total_count); } // 测试示例 console.log(buildFilledArray(['hello', 'there', 'world'], 15, null)); console.log(buildFilledArray(['hello', 'there', 'world'], 3, null)); console.log(buildFilledArray(['hello', 'there', 'world'], 4, null));
逻辑说明
- 当总填充量能被原数组长度整除时,每个元素后的填充数完全一致,比如示例中15-3=12,12/3=4,每个元素后加4个
null - 当总填充量不能整除时,前
extraFillCount个元素后会多一个填充值,比如total_count=4时,填充量为1,仅第一个元素后加1个null
这种写法逻辑清晰,时间复杂度为O(total_count),满足需求。
内容的提问来源于stack exchange,提问作者user1087973
相关产品推荐
相关产品推荐

