当前位置:网站首页>Es6: template string
Es6: template string
2022-07-28 08:19:00 【When is the bright moon 666】
Preface : I saw MDN Official documents of , Let me be one and two big . May fall into the trap of perfectionism : Always want to read all the knowledge about a certain aspect at once , Understand everything . Like I just wanted to check the words take, But all about take Read the phrase of , As a result, one didn't remember . Some usages may not be used from its birth to its later abandonment , There is no point in spending time on it . therefore , I want to introduce its most basic , The most important usage . Other unusual uses may be mentioned in a stroke .
One 、 Template string
A template string is a string literal that can be inserted into an expression .
stay ES6(ES2015) Introduction in , in addition , It also Can have multiple lines of text , In other words, the carriage return line feed character can be output directly .
1. Compare template string with traditional string
Traditional string literals use single quotation marks '' Or double quotes "", As shown below
var str = 'hello world';
var str2 = "hello world";
The template string uses inverted quotation marks (backquote) ``, As shown below
var str3 = `hello world`;
Inverse single quote position , As shown in the figure below , Press to input

Although there are differences in form , But as a string literal, it is completely equivalent in essence .

2. Template strings can be inserted into expressions ( a key )
The grammar is as follows
`${expression}`
brief introduction :expression It can be any constant 、 Variable 、 Function call . stay ${expression} Before and after , There can also be any other legal characters , for example `abc${expression}xyz`. Final ,${expression} It will be converted into string and string splicing before and after , If any .
When there is no string , We want to print the information of an object , Only string splicing .
var xiaoming = {
name: ' Xiao Ming ',
age: 14,
sex: 'male'
};
var bio = 'name: ' + xiaoming.name + ', age: ' + xiaoming.age + ', sex: ' + 'male';
console.log(bio);
Now? , There are only three properties , Splicing strings can also introduce . however , When there are many attributes of an object , Splicing strings will be time-consuming and laborious . At this time , You should use the template string .
var xiaoming = {
name: ' Xiao Ming ',
age: 14,
sex: 'male'
};
var bio = `name: ${
xiaoming.name}, age: ${
xiaoming.age}, sex: ${
xiaoming.sex}`;
console.log(bio);
Can achieve the same purpose 
An expression can be a constant 、 Variable 、 Function call , They all eventually return a value , This value will be converted to string type , Then splice with other characters . If it is a value of reference type , Will call the object toString Method , Finally, the returned string is spliced


3. Template strings can have multiple lines of text
Can be directly in `` Enter the carriage return line feed character
var str = ` I'm the first line I'm the second line `
Output effect 
This is not allowed in traditional characters , Insert line breaks directly
JavaScript Will report a mistake :

It is mainly applicable to strings containing HTML Tag scene . If it is a plain text string , You enter the carriage return string , This is the character in the code indentation will also be included .
Output effect

At this time , You can only delete the indented characters in the code , But it will affect the readability of the code , Do more harm than good . But if in the string html label , Finally insert into dom In the tree , Indented characters will be because html The blank folding phenomenon of , So you can use . If you simply use strings in your code , There is no need to use this function , It's simply a chicken rib .
Two 、 Student information loading demo
One small demo, Practice using template strings
The code is as follows :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style> span {
font-weight:bold; } </style>
</head>
<body>
<h1> Student information list </h1>
<ul id="list">
<li id='info'> Information loading ...</li>
</ul>
<script> const students = [ {
name: 'Alice', age: 20, sex: 'famale' }, {
name: 'Jimmy', age: 15, sex: 'male' }, {
name: 'xiaoxiao', age: 23, sex: 'female' } ]; const list = document.querySelector('#list'); let index = 0; const printTimer = setInterval(()=>{
if (index >= students.length) {
clearInterval(printTimer); document.getElementById('info').innerText = ' The information is loaded !'; } let liNode = document.createElement('li'); liNode.innerHTML = `<span>name: </span>${
students[index].name}, <span>age: </span>${
students[index].age}, <span>sex: </span>${
students[index].sex}`; list.appendChild(liNode); index ++; }, 2000) </script>
</body>
</html>
The effect is as follows :
边栏推荐
- 【17】建立数据通路(上):指令+运算=CPU
- flowable工作流所有业务概念
- Adjust the array order so that odd numbers precede even numbers - two questions per day
- What if the computer file cannot be deleted?
- DNA deoxyribonucleic acid modified platinum nanoparticles ptnps DNA | scientific research reagent
- 【300+精选大厂面试题持续分享】大数据运维尖刀面试题专栏(八)
- 【活动报名】云原生技术交流 Meetup,8 月 6 日广州见
- DNA modified rhodium RH nanoparticles rhnps DNA (DNA modified noble metal nanoparticles)
- 辨析覆盖索引/索引覆盖/三星索引
- Huawei Senior Engineer -- BGP routing filtering and community attributes
猜你喜欢
![[event registration] cloud native technology exchange meetup, see you in Guangzhou on August 6](/img/08/b892bd6c14d5ba3691f9b7def29c35.png)
[event registration] cloud native technology exchange meetup, see you in Guangzhou on August 6

Flowable workflow all business concepts

DNA-CuInSeQDs近红外CuInSe量子点包裹脱氧核糖核酸DNA

非关系型数据库之Redis【redis安装】

“蔚来杯“2022牛客暑期多校训练营2补题记录(DGHJKL)

Change the dataDir path after mysql8.0.16 installation

protobuf 基本语法总结

非关系型数据库之Redis【redis集群详细搭建】

The first common node of two linked lists -- two questions per day

These mobile security browsers are more than a little easy to use
随机推荐
Near infrared two region agzs quantum dots wrapped deoxyribonucleic acid dna|dna agzsqds (Qiyue)
Use ffmpeg to generate single image + single audio streaming video in batches
Chapter 01 introduction of [notes of Huashu]
[Google] solve the problem that Google browser does not pop up the account and password save box and cannot save login information
Tensorflow uses deep learning (II)
登录模式:单一服务器模式、单点登录、token模式
Merge two sorted linked lists - two questions per day
非关系型数据库之Redis【Jedis客户端+Jedis连接集群】
Change the dataDir path after mysql8.0.16 installation
Mysql中有哪些不同的表格?
OpenTSDB-时序数据库
Find out whether the number exists from the matrix
@Documented 的作用
[dry goods] 32 EMC standard circuits are shared!
The core packages and middleware required for golang development cover all areas of the project and are worth collecting
Can the variable modified by final be modified
数据化管理洞悉零售及电子商务运营——数据化管理介绍
DNA-CuInSeQDs近红外CuInSe量子点包裹脱氧核糖核酸DNA
滴滴SQL面试题之打车业务问题如何分析
How to analyze the taxi business problem of didi SQL interview question