当前位置:网站首页>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 :
边栏推荐
- QT uses semaphores to control threads (qsemaphore)
- protobuf 基本语法总结
- [book club issue 13] Chapter 2 notes on the packaging format and coding format of video files
- 深度学习基础宝典---激活函数、Batch Size、归一化
- 03 | project deployment: how to quickly deploy a website developed based on the laravel framework
- Opencv's practical learning of credit card recognition (4)
- [Google] solve the problem that Google browser does not pop up the account and password save box and cannot save login information
- Oracle local network service
- Opentsdb time series database
- 数据化管理洞悉零售及电子商务运营——数据化管理介绍
猜你喜欢

Oracle local network service

MPLS -- multi protocol label switching technology

These mobile security browsers are more than a little easy to use

【17】建立数据通路(上):指令+运算=CPU

【google】解决google浏览器不弹出账号密码保存框且无法保存登录信息问题

Change the dataDir path after mysql8.0.16 installation

Rk3568 development board installation system startup

谈谈DOM0,DOM1,DOM2,DOM3

Matplotlib绘图笔记基础直线、折线、曲线

Delete the nodes in the linked list - daily question
随机推荐
mysql,可以使用多少列创建索引?
Information system project manager must recite the core examination site (41) risk management plan
非关系型数据库之Redis【redis集群详细搭建】
In the task manager, the CPU speed displayed is greater than its maximum speed [main frequency]
03 | project deployment: how to quickly deploy a website developed based on the laravel framework
mysql,我们如何得到受查询影响的行数?
【13】 Adder: how to build a circuit like Lego (Part 1)?
The penultimate node in the linked list - Double finger
Brief introduction to ThreadLocal class
【13】加法器:如何像搭乐高一样搭电路(上)?
MPLS --- 多协议标签交换技术
The underlying principles of RDB persistence and AOF persistence of redis
QT uses semaphores to control threads (qsemaphore)
These mobile security browsers are more than a little easy to use
Merge two sorted linked lists - two questions per day
Redis of non relational database [jedis client +jedis connection cluster]
【300+精选大厂面试题持续分享】大数据运维尖刀面试题专栏(八)
【17】 Establish data path (upper): instruction + operation =cpu
MySQL query error [err] 1046 - no database selected
JUC atomic class: CAS, unsafe, CAS shortcomings, how to solve ABA problems in detail