• 深入理解ES6读书笔记2:模板字面量


    模板字面量提供了创建领域专用语言(domain-specific language,DSL)的语法,处理内容更安全。
    模板字面量的最简单语法,是使用反引号( ` )来包裹普通字符串。
    字符串中包含反引号,使用反斜杠( )转义。

    let message = `Hello world!`;
    console.log(message); // "Hello world!"
    console.log(typeof message); // "string"
    console.log(message.length); // 12
    let message2 = `\`Hello world!\``; 
    console.log(message2); // "`Hello world!`"

    多行字符串

    let message = `Hello 
      world!`;
    console.log(message);

    制造替换位

    替换位可以将任何有效的 JS 表达式嵌入到模板字面量中,并将其结果输出为字符串的一部分。
    替换位由起始的 ${ 与结束的 } 来界定,之间允许放入任意的 JS 表达式。
    可替换的除了变量名,还可以嵌入计算、函数调用等等。

    let count = 10,
        price = 0.25,
        message = `${count} items cost $${(count * price).toFixed(2)}.`;
    console.log(message); // "10 items cost $2.50."

    标签化模板

    一个模板标签能对模板字面量进行转换并返回最终的字符串值,标签在模板的起始处被指定,即在第一个 ` 之前,如下所示:

    let message = tag`Hello world`;

    tag 就是会被应用到 `Hello world` 模板字面量上的模板标签。
    第一个参数是个数组,包含被 JS 解释过的字面量字符串,随后的参数是每个替换位的解释值。

    let name = 'World'; 
    let message = tag`Hello ${name} !`;
    function tag(literals, ...substitutions) {
        let result1 = "";
        let result2 = "";
        for (let i = 0; i < literals.length; i++) {
            console.log('literals[', i, ']:', literals[i]);//literals[ 0 ]: Hello 
                                                           //literals[ 1 ]:  !
            result1 += literals[i];
        }
        for (let i = 0; i < substitutions.length; i++) {        
            console.log('substitutions[', i, ']:', substitutions[i]);//substitutions[ 0 ]: World
            result2 += substitutions[i];
        }
        return result2 + result1; // "WorldHello  !"    
    }
    console.log(message);

    模板字面量中的原始值

    模板标签也能访问字符串的原始信息,主要指的是可以访问字符在转义之前的形式。

    let message1 = `Hello
    world!`,
        message2 = String.raw`Hello
    world!`;
    console.log(message1);//"Hello
                          // world!"
    console.log(message2);//"Hello
    world!"
  • 相关阅读:
    Oracle DB 备份恢复目录
    Oracle DB 在恢复目录中注册数据库
    Flex中动态生成DataGrid以及动态生成表头
    Flex报错归类(三)
    Flex报错归类(二)
    QuickServer
    Oracle DB 创建恢复目录
    Oracle DB 创建恢复目录所有者
    Oracle DB 使用DBCA创建单实例ASM数据库用作恢复目录数据库
    OCP-1Z0-053-V12.02-628题
  • 原文地址:https://www.cnblogs.com/gdjlc/p/14516412.html
Copyright © 2020-2023  润新知