PCDotFan

To be an life & code artisan

ES6 - 模板字符串

JavaScript 0 评

在 ES5 时代,拼接字符串需要这样写:

    let Computer = {
      company: 'ThinkPad',
      name: 'Carbon X1',
      features: ['fast', 'inexpensive', 'squared-shape'],
      ram: '8G'
    }
    console.log('My computer is a ' + Computer.name + ' and it has ' + Computer.ram + ' RAM.');

实在是太惨了……就算是 PHP 也知道有个双引号能够解析字符串中的变量,而如今 模板字符串 即解决了这个问题:使用反引号括起需要解析的字符串,再将变量处理为 ${Variable} 这样的格式就可以达到无痛写字符串的效果:

    // ...
    console.log(`My computer is a ${Computer.name} and it has ${Computer.ram} RAM.`);
    // ...

实际上 ${} 并不仅仅能包裹变量——函数也行:

    let Computer = {
      company: 'ThinkPad',
      name: 'Carbon X1',
      features: ['fast', 'inexpensive', 'squared-shape'],
      ram: '8G',
      printIntroduction: function() {
        return `${this.name} and it has ${this.ram} RAM.`
      }
    }
    console.log(`My computer is a ${Computer.printIntroduction()}`);

MDN: 模板字面量也可以使用三元运算符( condition ? true : false ) 和 嵌套 nested!

Ex. ES6 实现 Todos


    let Computer = {
      company: 'ThinkPad',
      name: 'Carbon X1',
      features: [
        { feature: 'fast', truth: true },
        { feature: 'inexpensive', truth: false },
        { feature: 'squared-look', truth: true }
      ]
    }

    function renderFeatures() {
      return `${Computer.features.map(feature => `<li>${feature.feature} ${feature.truth ? '√' : '×' } </li>`).join('')}`
    }

    const template = `
      <div>
        Is ${Computer.name} worthy to be paid?
        <ul>
          ${renderFeatures()}
        </ul>
      </div>
    `
    document.write(template)

输出:

Is Carbon X1 worthy to be paid?
    - fast √
    - inexpensive ×
    - squared-look √

带标签的模板字符串(Tagged Template String)

MDN: 模板字符串的一种更高级的形式称为带标签的模板字符串。它允许您通过标签函数修改模板字符串的输出。 标签函数的第一个参数是一个包含了字符串字面值的数组(在本例中分别为“Hello”,“world”和"") 第二个参数,在第一个参数后的每一个参数,都是已经被处理好的替换表达式(在这里分别为“15”和“50”)。 最后,标签函数返回处理好的字符串。

Ex. 高亮标签

MDN:

https://i.loli.net/2017/11/10/5a051c1fe58af.jpg

   let Computer = {
      company: 'ThinkPad',
      name: 'Carbon X1',
      ram: '16G'
    }

    function highlight(strings, ...args) {
      let highlighted = args.map(arg => {
        return `<span class="highlighted">${arg}</span>` || '';
      })
      let composed = ''
      strings.forEach((current, index, ar) => {
        composed += `${current}${highlighted[index] || ''}`
      })
      return composed
    }
    let computerIntro = highlight`My computer is a ${Computer.name} and it has ${Computer.ram} RAM.`;
    document.body.innerHTML = `<p>${computerIntro}</p>`