JavaScript 学习-12.模板字符串(Template Strings)

Posted 上海-悠悠

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 不支持模板字面量。

以上是关于JavaScript 学习-12.模板字符串(Template Strings)的主要内容,如果未能解决你的问题,请参考以下文章

Python二分查找,字符串模板,textwrap模块,每天写写Python自然就会了,每日Python第2天

Django - Javascript 在模板中不起作用

JavaScript学习笔记

Django入门与实践-第12章:复用模板(完结)

[JavaScript语法学习]全面介绍String

Javascript学习--烟花