• [ES6] 11. String Templates


    ECMAscript 6 lets us use string templates to gain a lot more control over strings in JavaScript.

    var salutation = "Hello";
    var place = "New York";
    var greeting =`
        ${salutation}, I
    am    IN
    
        ${place}
    
    CITY
    `;
    
    console.log(greeting);
    
    /**
    
        Hello, I
    am    IN
    
        New York
    
    CITY
    
    */

    you can do expressions:

    var x = 1;
    var y = 2;
    
    var sum = `${x} + ${y} = ${ x + y }`;
    console.log(sum);  // 1 + 2 = 3

    basic introduction to tagging these string templates:

    var message = `It's ${new Date().getHours()}, I'm studying`;
    console.log(message);  // It's 13, I'm studying

    Now make those string as variable:

    <!DOCTYPE html>
    <html>
      <head>
        <script data-require="traceur@*" data-semver="0.0.0-20140302" src="https://traceur-compiler.googlecode.com/git/bin/traceur.js"></script>
        <script>
         traceur.options.experimental = true;
        </script>
        <script data-require="traceur@*" data-semver="0.0.0-20140302" src="https://traceur-compiler.googlecode.com/git/src/bootstrap.js"></script>
        <link rel="stylesheet" href="style.css" />
        <script src="script.js"></script>
      </head>
    
      <body>
          <script type="module">
            function tag(strings, ...values){
                if(values[0] < 20){
                    values[1] = "awake";
                }
                
                return `${strings[0]}${values[0]}${strings[1]}${values[1]}`;
            }
            
            var message = tag `It's ${new Date().getHours()}, I'am ${""}`;
            console.log(message);
          </script>
      </body>
    </html>
  • 相关阅读:
    记忆点
    数组的操作
    console.log()中的运算与打印事件
    ie9上传后下载json
    mysql使用on duplicate key update批量更新数据
    vue 弹出菜单
    mysql备份脚本
    uniapp+nodejs微信支付小程序版
    mycat初体验
    vscode格式化html标签属性不换行(vetur插件)
  • 原文地址:https://www.cnblogs.com/Answer1215/p/4115528.html
Copyright © 2020-2023  润新知