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

如何在不拆分单词的前提下将数组长元素拆分为两个元素

解决数组中长字符串按单词拆分并插入原位置的问题

需求说明

给定一个包含不同长度对话字符串的数组,需要将长度超过200字符的元素拆分为两个独立元素,拆分时不能截断单词(必须基于空格拆分),并且要在原数组的正确位置插入拆分后的后半部分,替换原长元素为前半部分。

示例

输入数组:

[
  "Hello there I'm shorter than 200 characters so do nothing with me",
  "I'm longer than 200 characters though so I should be split into two consecutive elements so that my first half stays where I am currently located in the array and my second half goes to the very next position in the array.",
  "I'm shorter than 200 so I just stay here as the last element."
]

期望输出:

[
  "Hello there I'm shorter than 200 characters so do nothing with me",
  "I'm longer than 200 characters though so I should be split into two consecutive elements so that my first",
  "half stays where I am currently located in the array and my second half goes to the very next position in the array.",
  "I'm shorter than 200 so I just stay here as the last element."
]

原代码的问题

你写的代码存在几个关键问题:

  • 使用forEach遍历原数组时直接修改数组(push),会导致遍历顺序混乱,而且新元素会被加到数组末尾,不是原元素的下一个位置
  • 直接用substring(0, element.length/2)拆分,会粗暴截断单词,不符合需求
  • 没有移除原来的长元素,导致数组里会保留原长元素加上错误拆分的内容

正确实现代码

我们可以通过倒序遍历数组来避免索引混乱,同时找到合适的拆分位置:

const myArray = [
  "Hello there I'm shorter than 200 characters so do nothing with me",
  "I'm longer than 200 characters though so I should be split into two consecutive elements so that my first half stays where I am currently located in the array and my second half goes to the very next position in the array.",
  "I'm shorter than 200 so I just stay here as the last element."
];

// 倒序遍历,避免修改数组时影响后续索引
for (let i = myArray.length - 1; i >= 0; i--) {
  const str = myArray[i];
  if (str.length <= 200) continue;

  // 找到第一个不超过200字符的最后一个空格位置
  let splitIndex = str.lastIndexOf(' ', 200);
  // 极端情况:如果前200字符里没有空格(比如超长单词),直接在200位置拆分
  if (splitIndex === -1) splitIndex = 200;

  const firstPart = str.substring(0, splitIndex).trim();
  const secondPart = str.substring(splitIndex).trim();

  // 替换原元素为前半部分,然后在当前索引后插入后半部分
  myArray.splice(i, 1, firstPart);
  myArray.splice(i + 1, 0, secondPart);
}

console.log(myArray);

代码解释

  1. 倒序遍历:从数组最后一个元素往前遍历,这样即使在当前索引后插入新元素,也不会影响还没遍历到的元素的索引
  2. 找拆分位置:用lastIndexOf(' ', 200)找到200字符以内最后一个空格的位置,保证拆分后前半部分不超过200字符且不截断单词
  3. 处理极端情况:如果前200字符里没有空格(比如一个超长单词),直接在200位置拆分(虽然不符合理想情况,但避免程序出错)
  4. 替换与插入:用splice方法先替换原长元素为前半部分,再在当前索引+1的位置插入后半部分,保证顺序正确

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 22:33:24