• JavaScript 学习12.模板字符串(Template Strings) 上海


    前言

    JavaScript 在ES6 新增了模板字符串(Template Strings)语法,其作用是可以在字符串中换行,以及将变量和表达式插入字符串。
    Internet Explorer 不支持模板字面量。

    模板字符串(Template Strings)

    模板字面量使用反引号 (``) 而不是单引号 ('') 或双引号 ("") 来定义字符串

    let a = `这个是一个模板字符串`;
    console.log(a);
    
    let b = `Hello World!`;
    console.log(b);
    

    可以在模板字符串中同时使用单引号和双引号

    let c = `hello "world", hei 'yoyo'`;
    

    也可以使用空格和换行定义多行文本

    let c = `<div>
        <h1>hello world!</h1>
    </div>`;
    console.log(c);
    

    引用变量

    可以在字符串中引用一个变量的值,也就是相当于python的字符串格式化, 使用语法

    ${变量名}

    简单示例

    let user = "yoyo";
    let x = `my name is ${user}`
    console.log(x);  // my name is yoyo
    

    可以引用一个字符串变量,也可以引用数字变量

    let user = "yoyo";
    let age = 20;
    let x = `my name is ${user}, age is ${age}`
    console.log(x);  // my name is yoyo, age is 20
    

    插入表达式

    模板字符串中也可以插入一个表达式

    let user = "yoyo";
    let age = 20;
    let x = `my name is ${user}, age is ${age+5}`
    console.log(x);  // my name is yoyo, age is 25
    

    插入表达式示例

    let x = 10;
    let y = 5;
    aa = `x - y 的值: ${x-y}`
    console.log(aa);  // x - y 的值: 5
    

    调用函数

    在模板字符串中可以调用函数

    function  fun1() {
        return "hello world"
    }
    let x = `fun1 return: ${fun1()}`;
    console.log(x);   // fun1 return: hello world
    

    也可以调用函数表达式

    const fun2 = function () {
        return "hello world"
    };
    let y = `fun1 return: ${fun2()}`;
    console.log(y);   // fun1 return: hello world
    

    备注:Internet Explorer 不支持模板字面量。

  • 相关阅读:
    Referenced file contains errors (http://www.springframework.org/...解决
    Echarts的提示(Tooltip)显示额外内容
    后端&前端零碎知识点和注意问题
    RocketMQ 4.5.1 双主双从异步复制环境搭建
    个人时间管理
    Windows系统封装教程
    你要如何衡量你的人生
    如何让你爱的人爱上你
    舔狗不会永远舔你的爱答不理和高冷
    关于小孩的教育问题
  • 原文地址:https://www.cnblogs.com/yoyoketang/p/16286894.html
Copyright © 2020-2023  润新知