模板字符串template strings

与一般字符串的区别

写法

一般字符串-写在单引号或者双引号里
模板字符串-写在反引号里

作用

模板字符串更方便注入

const person = {
    name: 'ZhangSan',
    sex: 'male',
    age: '18'
};
// const info = '姓名:' + person.name + '性别:' + person.sex + '年龄:' + person.age;
const info = `姓名:${person.name},性别:${person.sex},年龄:${person.age}`;
console.log(info);

空格换行或缩进 会保留在输出之中

换行输出3种方法
方法1:一般字符串

const info = '第一行\n第二行';

方法2:模板字符串之使用

const info = `第一行\n第二行`;

方法3:模板字符串之保留换行

const info = `第一行
第二行`;
console.log(info);

特别地,转义

const info = `\``;
const info = `\\`;
const info = `'`;

用${}注入

const username = 'Alex';
const person = { age: 18, sex: 'male' };
const getSex = function (sex) {
    return sex === 'male' ? '男' : '女';
};
const info = `${username},${person.age},${getSex(person.sex)}`;
console.log(info);

应用-学生信息表

<p>学生信息表</p>
<ul id="list">
	<li>信息加载中</li>
</ul>
<script>
	const students = [{
	    name: 'ZS',
	    sex: 'male',
	    age: 18,
	}, {
	    name: 'LS',
	    sex: 'female',
	    age: 20,
	}, {
	    name: 'WW',
	    sex: 'male',
	    age: 21,
	}];
	const list = document.getElementById('list');
	let html = '';
	for (let i = 0; i < students.length; i++) {
	    html += `<li>${students[i].name},${students[i].sex},${students[i].age}</li>`;
	}
	list.innerHTML = html;
</script>

版权声明:本文为chonger_feifei原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。