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

JavaScript多字符串拆分合并异常:仅最后一项结果保留

问题排查与解决

问题原因

你的代码在循环中每次执行 splitted = books[i].split(/[\s]+/) 时,都是直接将 splitted 变量重新赋值为当前字符串拆分后的数组,之前存储的内容会被完全覆盖,因此最终只保留了最后一个字符串的拆分结果。

修正方案

方案1:使用push结合展开运算符

通过展开运算符将每次拆分得到的数组元素逐个添加到splitted中,避免覆盖原有内容:

var books = new Array()
var a = "Lorem Ipsum dolor sit amet"
var b = "never gonna give you up"
var c = "another string variable"
books.push(a); books.push(b); books.push(c)

var splitted = []
for (let i = 0; i < books.length; i++) {
  splitted.push(...books[i].split(/[\s]+/))
}
console.log(splitted)

方案2:使用concat合并数组

每次将拆分后的数组与splitted合并,生成新的数组赋值给splitted:

var books = new Array()
var a = "Lorem Ipsum dolor sit amet"
var b = "never gonna give you up"
var c = "another string variable"
books.push(a); books.push(b); books.push(c)

var splitted = []
for (let i = 0; i < books.length; i++) {
  splitted = splitted.concat(books[i].split(/[\s]+/))
}
console.log(splitted)

方案3:更简洁的flatMap写法

利用数组的flatMap方法,一步完成遍历、拆分和扁平化合并:

var a = "Lorem Ipsum dolor sit amet"
var b = "never gonna give you up"
var c = "another string variable"
const books = [a, b, c]
const splitted = books.flatMap(str => str.split(/[\s]+/))
console.log(splitted)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 21:20:37