javascript - 将数组中的字符串组合到一定长度

标签 javascript arrays

var chars = 100;

var s = [
"when an unknown printer took a galley of type and scrambled it to make a type specimen book",  //contains 91 chars
"essentially unchanged. It was popularised in the 1960s with the release",          //contains 71 chars
"unchanged essentially. popularised It was in the 1960s with the release",          //contains 71 chars
"It is a long established", //contains 24 chars
"search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years",    //contains 121 chars
"injected humour and the like"          //contains 28 chars
]

如果当前句子中的字符数少于变量chars=100,我想加入(通过\n)下一个句子

如果chars=100那么

1) s[0] 小于 100,所以我必须加入 s[1]s[1]

2) s[2] 小于 100,所以我必须加入 s[3] 但合并后它们仍然是 95,因此我需要进一步加入s[4]

3) 当列表为空时显示s[5]

预期输出:

1) 当一位不知名的打印商拿走一套字体并将其打乱以制作一本字体样本簿时 基本没有变化。它在 20 世纪 60 年代随着发行而流行

2) 本质上没有变化。流行于 20 世纪 60 年代,随着发布 这是一家历史悠久的 搜索“lorem ipsum”将发现许多仍处于起步阶段的网站。多年来已经发展出各种版本

3)注入(inject)幽默之类

如何用最快的代码在 JS 中实现?

var x = "";
var y = [];
for (var i = 0; i < s.length; i++) {
 if(x.length<100)
 {
    x=x+s[i];
    continue;
 }
y.push(x)
x="";

}

y.push(x)
console.log(y.join("\n\n"));

最佳答案

一种方法是仅解析数组一次,但使用另一个数组作为结果:

var chars = 100;

var s = [
    "when an unknown printer took a galley of type and scrambled it to make a type specimen book",
    "essentially unchanged. It was popularised in the 1960s with the release",
    "unchanged essentially. popularised It was in the 1960s with the release", //contains 71 chars
    "It is a long established", //contains 24 chars
    "search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years", //contains 121 chars
    "injected humour and the like" //contains 28 chars
  ],
  out = [],
  tmp;

s.forEach((str, index) => {
  tmp = tmp ? tmp + '\n' + str : str;
  if (tmp.length > chars || index == s.length - 1) {
    out.push(tmp);
    tmp = null;
  }
});

console.log(out.join('\n\n'));

关于javascript - 将数组中的字符串组合到一定长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47031239/

相关文章:

javascript - type=”number” 和基于文化的小数点分隔符的 html 标签输入

javascript - 如何在标记之间获取代码

javascript - 添加不带变量的 .val()

c - 字符串大小等于字符数

c# - 如何在我的 C# Controller 中获取 Ajax post 数组?

c - 程序不会使用正确的数组值

javascript - 如何在查找栏文本更改时引发事件

javascript - JS : checking object with key vs hasOwnProperty?

javascript - 根据属性是否存在对对象数组进行排序

javascript - 对日期为 JavaScript 的字符串数组进行排序