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 不支持模板字面量。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
2020-05-18 docker学习14-配置 docker 阿里云/腾讯云加速器