我应该将长字符串缩短为较短的子字符串吗

Should I shorten long strings into shorter sub strings?

本文关键字:字符串 我应该      更新时间:2024-03-01

我在一个我现在记不清的地方听说,将较长的字符串缩短为较短的子字符串是一个明智的想法。我应该这样做吗?优点和缺点是什么?

样品:

var str = "some extremly long string for the sample I am making for this Stack Overflow question. Must add more words to make longer.";
alert(str);

var str1 = "some extremely long string";
var str2 = "for the sample I am making";
var str3 = "for this Stack Overflow question.";
var str4 = "Must add more words to make longer.";
alert(str1 +str2 +str3 +str4);

您的两个版本不等效,因为连接的版本缺少空格。

如果你确实想拆散字符串,加入它们通常被认为是一种很好的做法:

var str = [
    "some extremely long string",
    "for the sample I am making",
    "for this Stack Overflow question.",
    "Must add more words to make longer."
 ].join(" ");

我经常看到这种模式,它确实更可读IMO.

随着ES6的普及,更多的人可能开始使用模板字符串提供的多行功能:

var str = `some extremely long string 
for the sample I am making 
for this Stack Overflow question. 
Must add more words to make longer.`;

我能想到的唯一原因是可读性。在源代码中有一行很长的代码是不太可读的。你的问题清楚地说明了这一点:在第一个例子中,必须依靠水平滚动来读取字符串;第二个例子没有这样的问题。

有关如何在JavaScript中拆分长字符串文字的讨论,请参阅另一个问题的答案。

我不知道有任何这样的优化。如果是可读性问题,可以使用反斜杠来编写多行字符串文字:

var string = "some extremely long string'
 for the sample I am making'
 for this Stack Overflow question.'
 Must add more words to make longer.";