【发布时间】:2020-01-29 16:32:21
【问题描述】:
我正在尝试有条件地拆分数组中的每个字符串。这是我的数组。
const categories = [
"Department of Natural Science",
"Department of public health and sanitation",
"Department of culture and heritage of state"
];
再次通过拆分每个字符串,我想将其更改为数组。该数组包含几个字符串块。例如。通过拆分Department of culture and heritage of state 字符串,我希望将其分开Department of Natural Science。在这里,我想创建每个不同的块如果块包含超过 13 个字符。这就是 Natural 和 Science 分开的原因,因为如果我们将它们的长度相加,它就会变成 14 。
这是我尝试过的。
const categories = [
"Department of Natural Science",
"Department of public health and sanitation",
"Department of culture and heritage of state"
];
const arrayOfAllString = []; // results at the end
categories.map(cur => {
// looping the array
const splitedItems = cur.trim().split(" "); // splitting the current string into words
const arrayOfSingleString = []; //
let str = "";
splitedItems.map(item => {
// looping the array of splitted words
if (str.length + item.length > 13) {
// trying to make a chunk
arrayOfSingleString.push(str);
str = ""; // clearing the str because it has been pushed to arrayOfSingleString
} else {
str = str.concat(item + " "); // concat the str with curent word
}
});
arrayOfAllString.push(arrayOfSingleString);
});
console.log(arrayOfAllString);
我的预期结果会是这样的:
arrayOfAllString = [
["Department of", "Natural", "Science"],
["Department of", "public health", "and", "sanitation"],
["Department of", "culture and", "heritage of", "state"]
];
【问题讨论】:
-
"字符长度超过 13 个单词"。您的所有字符串都不包含超过 13 个单词。你能说出你真正的意思吗?
标签: javascript arrays split concat