【发布时间】:2017-10-29 15:18:25
【问题描述】:
重复:Combining strings in an array upto certain length
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
如果chars=100 那么
1) s[0] 小于 100,所以我必须加入 s[1] 和 s[1]
2) s[2] 小于 100,所以我将不得不加入 s[3],但在组合它们之后仍然是 95,因此我需要进一步加入 s[4]
3) 列表为空时显示s[5]
预期输出:
1) 当一个不知名的印刷商拿了一个打字机,并把它打乱成一个打字样本 基本不变。它在 1960 年代随着发布而普及
2) 基本不变。普及它是在 1960 年代发布的 这是一个建立已久的 搜索“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"));
【问题讨论】:
-
请不要清除问题的内容。如果您认为它对任何未来的读者没有帮助,请将其删除。
标签: javascript arrays performance multidimensional-array