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

时间:2017-10-31 08:50:46

标签: 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
]

如果当前句子中的字符数 LESS 而不是变量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 个答案:

答案 0 :(得分: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'));