You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从数组末尾的0索引开始依次替换指定输入值?

问题与解决方案

需求描述

现有数组:

let arr = ["1", "0", "0", "0", ".", "0", "0"]

希望实现:输入一组值(如5,3,2)时,从数组的最后一个0的索引开始,依次向前将0替换为输入的值,最终得到:

updatedArray = ["1", "0", "0", "5", ".", "3", "2"]

请问该需求是否可实现?

现有代码分析

我尝试了以下查找0索引并替换最大索引值的代码:

const stringValueArray = stringValue.split('');

const emptyStringIndices: number[] = [];
stringValueArray.forEach((element, index) => {
  if (element === '0') {
    emptyStringIndices.push(index);
  }
});
const highestIndex = Math.max(...emptyStringIndices);

stringValueArray[highestIndex] = value;

const newValue = stringValueArray.join('');
return newValue;

这段代码仅能替换单个最大索引的0,无法满足多值依次替换的需求。

可行实现方案

该需求完全可以实现,核心思路如下:

  • 先找出数组中所有0的索引,按从大到小排序(确保从最后一个0开始往前处理)
  • 遍历输入值列表,依次将值替换到对应的0索引位置

具体实现代码:

function replaceZeros(originalArr: string[], values: number[]): string[] {
  // 复制原数组,避免修改原始数据
  const arr = [...originalArr];
  // 筛选所有0的索引并降序排序
  const zeroIndices = arr
    .map((item, idx) => item === '0' ? idx : -1)
    .filter(idx => idx !== -1)
    .sort((a, b) => b - a);

  // 依次替换对应位置的0
  values.forEach((val, idx) => {
    if (zeroIndices[idx] !== undefined) {
      arr[zeroIndices[idx]] = val.toString();
    }
  });

  return arr;
}

// 测试示例
const originalArr = ["1", "0", "0", "0", ".", "0", "0"];
const inputValues = [5, 3, 2];
const updatedArray = replaceZeros(originalArr, inputValues);
console.log(updatedArray); // 输出: ["1", "0", "0", "5", ".", "3", "2"]

代码说明

  • 复制原数组是为了避免修改原始数据,保证数据安全性
  • 通过map+filter筛选出所有0的索引,再用sort((a,b)=>b-a)实现降序排列,确保第一个索引是数组最后一个0的位置
  • 遍历输入值时,如果输入值数量超过0的数量,多余的值会被忽略,避免出现索引越界问题

内容的提问来源于stack exchange,提问作者Kaito Pader

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 04:32:30