我应该将长字符串缩短为较短的子字符串吗?
Should I shorten long strings into shorter sub strings?
我在某个地方听说过,我现在记不清了,将较长的字符串缩短为较短的子字符串是一个聪明的主意。我应该这样做吗?有什么优缺点?
样本:
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);
我能想到的这样做的唯一原因是可读性。源代码中有一行很长的代码可读性很差。您的问题很好地说明了这一点:必须依靠水平滚动来读取第一个示例中的字符串;第二个例子没有这个问题。
有关如何在 JavaScript 中拆分长字符串文字的讨论,请参阅 this answer 另一个问题。
我不知道有任何此类优化。如果是可读性问题,您可以使用反斜杠编写多行字符串文字:
var string = "some extremely long string\
for the sample I am making\
for this Stack Overflow question.\
Must add more words to make longer.";
您的两个版本不等同,因为连接后的版本缺少空格。
如果您确实想要拆分字符串,加入它们通常被认为是一种很好的做法:
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(" ");
我经常看到这种模式,在我看来它确实更具可读性。
随着 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.`;
我在某个地方听说过,我现在记不清了,将较长的字符串缩短为较短的子字符串是一个聪明的主意。我应该这样做吗?有什么优缺点?
样本:
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);
我能想到的这样做的唯一原因是可读性。源代码中有一行很长的代码可读性很差。您的问题很好地说明了这一点:必须依靠水平滚动来读取第一个示例中的字符串;第二个例子没有这个问题。
有关如何在 JavaScript 中拆分长字符串文字的讨论,请参阅 this answer 另一个问题。
我不知道有任何此类优化。如果是可读性问题,您可以使用反斜杠编写多行字符串文字:
var string = "some extremely long string\
for the sample I am making\
for this Stack Overflow question.\
Must add more words to make longer.";
您的两个版本不等同,因为连接后的版本缺少空格。
如果您确实想要拆分字符串,加入它们通常被认为是一种很好的做法:
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(" ");
我经常看到这种模式,在我看来它确实更具可读性。
随着 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.`;