首页 > 代码库 > 多行字符串,引号与反引号

多行字符串,引号与反引号

  大家都知道写 js 时,字符串都是用单引号或者双引号引着的,而一行写不下回车换行的时候,会被自动变成多段字符串并用 + 号来拼接上,比如这样:

<!DOCTYPE html>
<html>
    <head>
        <meta charset=‘utf-8‘>
    </head>
    <body>
        <div id=‘d1‘>111</div>
        <script>
            document.write(
                <style> +
                *{ +
                color:blue; + 
                font-size:20px; +
                } + 
                </style>
            )
        </script>
    </body>
</html>

  这样看着显得很乱,而且不易阅读,于是我们可以使用反引号来整理这段代码,它能够良好的保证我们代码的编写格式,并且不会出现 + 号拼接的情况,允许多段代码存在,like this:

<!DOCTYPE html>
<html>
    <head>
        <meta charset=‘utf-8‘>
    </head>
    <body>
        <div id=‘d1‘>111</div>
        <script>
      document.write(`
        <style>
          *{
            color:blue;
            font-size:20px;
          }
        </style>`
      )
        </script>
    </body>
</html>

  是不是比多段引号字符串更容易看懂了呢。

多行字符串,引号与反引号