javascript - 处理长 write() 参数的最佳方法是什么?

标签 javascript readability

更新:感谢大家的回复。我没有意识到 document.write() 已被弃用。为学习栏目再添一个档次。我将采纳此处发布的建议,但保留原始问题,以便给出的答案在原始问题的上下文中有意义。

<小时/>

我正在编写一些相当长的 write() 参数,并考虑语法、可读性和性能,尝试确定以下哪个示例最适合遵循。我应该吗

a.将它们全部放在一行上:

<script>

    var someVariable = "(<a href=\"http://www.example.com\">Link<\/a>)";

    document.write("<p>Supergroovalisticprosifunkstication and Supercalifragilisticexpialidocious are very long words.</p>" + someVariable + "<p>Dociousaliexpisticfragilicalirepus is Supercalifragilisticexpialidocious spelled backwards.</p>" + someVariable);

</script>

b.通过添加换行符来分解它们,以提高可读性:

<script>

    var someVariable = "(<a href=\"http://www.example.com\">Link<\/a>)";

    document.write("<p>Supergroovalisticprosifunkstication and Supercalifragilisticexpialidocious are very long words.</p>" 
        + someVariable
        + "<p>Dociousaliexpisticfragilicalirepus is Supercalifragilisticexpialidocious spelled backwards.</p>" 
        + someVariable);

</script>

c.使用多个变量将它们分解:

<script>

    var someVariable = "(<a href=\"http://www.example.com\">Link<\/a>)";

    var partOne = "<p>Supergroovalisticprosifunkstication and Supercalifragilisticexpialidocious are very long words.</p>"; 
    var partTwo = "<p>Dociousaliexpisticfragilicalirepus is Supercalifragilisticexpialidocious spelled backwards.</p>"; 

    document.write(partOne + someVariable + partTwo + someVariable);

</script>

提前致谢。

最佳答案

我的直觉 react 是:不要这样做。 (你的例子很糟糕,你不应该在行为层中编写大块内容。)

每当你必须这样做时,要么连接:

var longVar = 'asdfasdf asdf asdf asdfasdf asdfasdf asdf asdfasdf' +
    ' fasdf s9d0af asdf asdf0s,dv z-xcfva-sdfmwaert ' +
    'qersdfasdfasdfasdfasdf';
document.write(longVar);

或者,如果它变得非常长,使用连接数组可能会提高性能:

var longVar = [
    'asdfasdf asdf asdf asdfasdf asdfasdf asdf asdfasdf',
    ' fasdf s9d0af asdf asdf0s,dv z-xcfva-sdfmwaert ',
    'qersdfasdfasdfasdfasdf'
].join('');
document.write(longVar);

关于javascript - 处理长 write() 参数的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/238941/

相关文章:

javascript - Google Script,如何使用正则表达式将一行从 Sheet1 复制到 Sheet2 而不是一个单元格?

javascript - 我们如何利用 beginPath() Canvas 方法?

readability - 哪种配色方案最适合阳光下的可读性?

SQL 可读性 : commas better at the end or at the beginning of select list?

没有空格的 YAML 折叠

javascript - 仅使用 javascript 或 jquery 列出带括号的列表?

javascript - 下划线不会从 html 中消失

Javascript:使用递归将多维数组就地展平

java - 给 Java 程序员的 Python 可读性提示

coding-style - 如何在研究报告中格式化代码