开发者问题收集

将字符串组合成一个数组,直到达到一定的长度

2017-10-31
92
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) 注入幽默等

如何用最快的代码在 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"));
1个回答

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

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'));
bluehipy
2017-10-31