es6+最佳入门实践(14)

14.模版字符串

模版字符串(template string)是增强版的字符串,定义一个模版字符串需要用到反引号

let s = `这是一个模版字符串`
console.log(s)

14.1.模版字符串的应用场景

在es5中,我们经常会遇到字符串拼接的情况,例如:输入标题1-6

for(let i = 1; i <= 6; i++){
    document.write('<h'+i+'>标题'+i+'</h'+i+'>')
}

在es6中,支持模版字符串的写法,我们可以写成下面这种形式

for(let i = 1; i <= 6; i++){
    document.write(`<h${i}>标题${i}</h${i}>`)
}

模版字符串的好处就是可以使得拼接字符串非常的方便,例如:

let htmlStr = `
    <div id="dialog-wrap">
        <div class="dialog-title">
            <p class="title-text"></p>
        </div>
        <div class="dialog-content">
            <ul class="list-group"></ul>
        </div>
    </div>
`
document.body.innerHTML = htmlStr;

视频教程地址:http://edu.nodeing.com/course/50

猜你喜欢

转载自www.cnblogs.com/dadifeihong/p/10358144.html