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 不支持模板字面量。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值