zoukankan      html  css  js  c++  java
  • (译文)学习ES6非常棒的特性-字符串常量基础

    字符串常量基础

    在ES2015之前我们是这么拼接字符串的:

    var result = 10;
    var prefix = "the first double digit number I learnt was ";
    var assembled = prefix + result.toString();
    console.log(assembled); // logs => 'the first double digit number I learnt was 10'

    在ES2015我们可以这么做:

    var result = 10;
    var assembled = `the first double digit number I learnt was ${result}`;
    console.log(assembled); // logs => 'the first double digit number I learnt was 10'

    通过 ${}引用外部的变量

    字符串常量拼接里面遍历

    假设我们有一个数组,我们怎么遍历它:

    var data = [
      // Data here
    ];
    // loop through the data
    data.forEach((datarecord, idx) => {
      // for each record we call out to a function to create the template
      let markup = createSeries(datarecord, idx);
      // We make a div to contain the resultant string
      let container = document.createElement("div");
      container.classList.add("as-Series");
      // We make the contents of the container be the result of the function
      container.innerHTML = markup;
      // Append the created markup to the DOM
      document.body.appendChild(container);
    });
    function createSeries(datarecord, idx) {
      return `
        <div class="a-Series_Title">${datarecord.Title}</div>
      `;
    }

    完整的拼接方法类似这样:

    function createSeries(datarecord, idx) {
      return `
        <h2 class="a-Series_Title">${datarecord.Title}</h2>
        <p class="a-Series_Description">
          <span class="a-Series_DescriptionHeader">Description: </span>${datarecord.Description}
        </p>
        <div class="a-EpisodeBlock">
          <h4 class="a-EpisodeBlock_Title">First episodes</h4>
        </div>
      `;
    }

    如果数据里面又有一个数组,怎么遍历?

    function createSeries(datarecord, idx) {
      return `
        <h2 class="a-Series_Title">${datarecord.Title}</h2>
        <p class="a-Series_Description">
          <span class="a-Series_DescriptionHeader">Description: </span>${datarecord.Description}
        </p>
        <div class="a-EpisodeBlock">
          <h4 class="a-EpisodeBlock_Title">First episodes</h4>
          ${datarecord.Episodes.map((episode, index) =>
            `<div class="a-EpisodeBlock_Episode">
                <b class="">${index+1}</b>
                <span class="">${episode}</span>
            </div>
            `
          )}
        </div>
    `};

    ok. 然后打印出来:

    Episodes
    1 Homecoming
    ,
    2 New Colossus
    ,
    3 Champion
    ,
    4 Away
    ,
    5 Paradise
    ,
    6 Forking Paths
    ,
    7 Empire of Light
    ,
    8 Invisible Self

    多了一个默认的逗号,怎么办。

    ${datarecord.Episodes.map((episode, index) =>
      `<div class="a-EpisodeBlock_Episode">
          <b class="">${index+1}</b>
          <span class="">${episode}</span>
      </div>
      `
    ).join("")}

    通过join方法处理一下就好了。

    字符串常量里面用if/else

    ${datarecord.Ended === true ? `` : `<div class="a-Series_More">More to come!</div>`}

    使用返回另外一个值的函数

    假设我们有这样一个函数

    const add = (a, b) => a + b;
    function getRatingsAverage(ratings) {
      return ratings.reduce(add) / ratings.length;
    }

    这样使用就可以了:

    `<div class="a-UserRating">Average user rating: <b class="a-UserRating_Score">${getRatingsAverage(datarecord.UserRatings)}</b></div>`

    安全

    看一个例子:

    var username = 'craig<script>alert("XSS")</' + 'script>';
    document.write(`<p>Hi ${username}</p>`);

    用户输入了一个js代码,然后我们直接填充到了username里面。这个时候会导致浏览器弹出一个alert。 这样肯定是不行的。

    一般我们需要escape方法转义一下,或者用textContent。

    // HTML Escape helper utility
    var util = (function () {
      // Thanks to Andrea Giammarchi
      var
        reEscape = /[&<>'"]/g,
        reUnescape = /&(?:amp|#38|lt|#60|gt|#62|apos|#39|quot|#34);/g,
        oEscape = {
          '&': '&amp;',
          '<': '&lt;',
          '>': '&gt;',
          "'": '&#39;',
          '"': '&quot;'
        },
        oUnescape = {
          '&amp;': '&',
          '&#38;': '&',
          '&lt;': '<',
          '&#60;': '<',
          '&gt;': '>',
          '&#62;': '>',
          '&apos;': "'",
          '&#39;': "'",
          '&quot;': '"',
          '&#34;': '"'
        },
        fnEscape = function (m) {
          return oEscape[m];
        },
        fnUnescape = function (m) {
          return oUnescape[m];
        },
        replace = String.prototype.replace
      ;
      return (Object.freeze || Object)({
        escape: function escape(s) {
          return replace.call(s, reEscape, fnEscape);
        },
        unescape: function unescape(s) {
          return replace.call(s, reUnescape, fnUnescape);
        }
      });
    }());
    // Tagged template function
    function html(pieces) {
        var result = pieces[0];
        var substitutions = [].slice.call(arguments, 1);
        for (var i = 0; i < substitutions.length; ++i) {
            result += util.escape(substitutions[i]) + pieces[i + 1];
        }
        return result;
    }
    var username = "Domenic Denicola";
    var tag = "& is a fun tag";
    console.log(html`<b>${username} says</b>: "${tag}"`);

    以上就是今天的内容,感谢阅读。

    更多内容,点击阅读原文:
    https://benfrain.com/html-templating-with-vanilla-javascript-es2015-template-literals/
    作者知乎/公众号:前端疯

  • 相关阅读:
    js实现页面触摸滑动
    关于js中window.location.href,location.href,parent.location.href,top.location.href的用法
    eclipse tomcat 插件
    Eclipse中的Web项目自动部署到Tomcat的webapp目录下
    i=i+1与i+=1的区别及效率(Java)
    Java super和this
    Thinkphp
    单一静态网页如何实现点击左边菜单在右边展现内容
    dbda封装类(包括:返回二维数组、Ajax调用返回字符串、Ajax调用返回JSON)
    图片轮播代码
  • 原文地址:https://www.cnblogs.com/xunxing/p/b82256a7d6ccbe82ac492e0b4103544a.html
Copyright © 2011-2022 走看看