当前位置:网站首页>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 :
边栏推荐
- 解析树形结构 js
- node(一)
- ArcGIS JS 地图内外网环境判断问题
- CLion调试redis6源码
- 登录模式:单一服务器模式、单点登录、token模式
- Talk about synchronous, asynchronous, blocking and non blocking
- MPLS -- multi protocol label switching technology
- 非关系型数据库之Redis【Jedis客户端+Jedis连接集群】
- The underlying principles of RDB persistence and AOF persistence of redis
- 任务管理器中,显示的CPU速度大于它的最大速度【主频】
猜你喜欢

Understanding of spark operator aggregatebykey

数据化管理洞悉零售及电子商务运营——数据化管理介绍

Elaborate on common mode interference and differential mode interference
![[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

@The role of documented

And is two numbers of S - two questions per day

Synthesis of dna-ag2sqds DNA modified silver sulfide Ag2S quantum dots

"Wei Lai Cup" 2022 Niuke summer multi school training camp 2 supplementary question record (dghjkl)

Common solutions for distributed ID - take one

XSS knowledge points and 20 character short domain name bypass
随机推荐
DNA modified rhodium RH nanoparticles rhnps DNA (DNA modified noble metal nanoparticles)
JUC原子类: CAS, Unsafe、CAS缺点、ABA问题如何解决详解
(Reprinted) plantuml Quick Guide
Parse tree structure JS
Mysql, how many columns can be used to create an index?
Five screens, VR, projection, "Wei Xiaoli" rolled up on the intelligent cockpit
Detailed explanation of random number generated by random class
Tensorflow uses deep learning (II)
awk从入门到入土(16)awk变量类型探讨--关于数字和string两种类型
DNA cuinseqds near infrared CuInSe quantum dots wrapped deoxyribonucleic acid DNA
【花书笔记】 之 Chapter01 引言
【17】 Establish data path (upper): instruction + operation =cpu
Basic dictionary of deep learning --- activation function, batch size, normalization
[book club issue 13] Chapter 2 notes on the packaging format and coding format of video files
Fxksmdb.exe process description
Google and Stanford jointly issued a document: why do we have to use large models?
【17】建立数据通路(上):指令+运算=CPU
使用FFmpeg来批量生成单图+单音频的一图流视频
Elaborate on common mode interference and differential mode interference
@Documented 的作用