<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>模板字符串</title>
</head>
<body>
<script>
/*
ES5字符串拼接
*/
const person = 'xyz';
const age = 21;
const sentence = person + " is " + age + " years old.";
console.log(sentence);
/*
ES6字符串拼接(模板字符串)
*/
const person1 = 'xyz';
const age1 = 22;
const sentence1 = `${person1} is ${age1} years old.`; //注意:是这是(`)反引号,里面写入字符串,如果需要嵌入变量、对象的属性、函数、表达式,就用${}
console.log(sentence1); //结果为:xyz is 22 years old.
const sentence2 = `${person1} is ${age1*2} years old.`;
console.log(sentence2); ////结果为:xyz is 44 years old.
//-------------------------------------------------------------------------
/*
ES5模板写法
*/
const template = '<div class="greet"><p>Hello</p></div>'; //这样不利于理解层级关系
console.log(template);
//解决方法1:利用反斜杠换行
const template1 = '\
<div class="greet">\
<p>Hello</p>\
</div>';
console.log(template1);
//解决方法2:使用数组的方法
const template2 = [
'<div class="greet">',
'<p>Hello</p>',
'</div>'
].join('');
console.log(template2);
/*
ES6模板写法
在反引号中如果把层级关系排列的比较清楚并且去掉多余的空格,就用:trim()方法
*/
const template3 = `
<div class="greet">
<p>Hello</p>
</div>
`.trim();
console.log(template3);
</script>
</body>
</html>
字符串扩展→模板字符串
猜你喜欢
转载自blog.csdn.net/JEFF_luyiduan/article/details/91489071
今日推荐
周排行