深入了解 ES6 模板字面量

503 阅读1分钟

模板字面量

模板字面量是ES6引入的特性(在 ES2015 规范的先前版本中被称为“模板字符串”),它允许我们在字符串字面量中插入表达式(expression),相比于普通的字符串字面量,其更像是一个特殊的立即执行函数(IIFE)。
模板字面量使用反引号 (`) 来代替普通字符串中的用双引号和单引号。(字面量:JavaScript 代码中用来表示一个固定的值,可以理解为"代码文字表面上的意义的常量”,即所见即所得)

插入表达式(expression)

语法如下:${expression}

  • expression 可以是任意运算、常量、变量、函数调用。
  • ${expression} 本质上是一个占位符,占位符中的表达式和周围的文本会一起传递给一个默认函数,该函数负责将所有的部分连接起来。
  • 模版字面量内使用反引号(`)时,需要在它前面加转义符(\)。
  • 模版字面量内使用斜杆(\)时,需要在它前面加转义符(\)。
const things = ['day', 'moon', 'you'];
const getNumber = () => things.length;
const strOne = `there is ${getNumber()} things I love in the world`;
// 这里things 发生隐式转换 toString
const strTwo = `${strOne}, ${things}`;
console.log(strTwo);
// there is 3 things I love in the world, day,moon,you

插入多行文本

模板字面量中新行中插入的任何字符都是模板字符串中的一部分。

// 普通字符串,不允许直接直接插入换行符,否则会报错
console.log('it is line one\n' + 'it is line two');

// 模板字面量
console.log(`it is line one
it is line two`);

标签模板字面量

模板字面量的高级用法,标签可以用函数解析模板字面量。标签函数的第一个参数是由表达式分割(参考 Array.split)的字符串数组,其余参数则与表达式相关。

const things = ['day', 'moon', 'you'];

// 使用剩余参数语法,将一个不定数量参数表示为一个数组。
function getParam(strings, ...values) {
    console.log(strings);
    console.log(values);
    for (const i in values) {
        if (typeof values[i] === 'function') {
            console.log(values[i]());
        } else {
            console.log(values[i]);
        }
    }
}
getParam`there is ${() => things.length} things I love in the world`;
// strings => ["there is ", things I love in the world']
// values => [f] => [() => things.lengths]

// 拼接字符串
function tag(strings, ...values) {
    return strings.reduce(function (s, v, index) {
        return s + (index > 0 ? values[index - 1] : '') + v;
    });
}
const str = tag`there is ${things.length} things I love in the world, ${things}`;
console.log(str);