ES6:模板字符串

     为了能够让前端更加方便的拼接,操作字符串,ES6出了模板字符串。


  • 传统的字符串模板 :在传统的Javascript中,如果我们对DOM进行操作,字符串模板通常采用加号( + )进行字符串拼接。
  • ES6模板字符串 :以反引号( ` )表示普通的字符串,也可以表示多行字符串,同时还可以插入变量(代替传统的加号拼接)。

一、语法

     模板字符串是用反引号``代替常规字符串的单引号‘’或者双引号"",从而让字符串拥有可将其中部分字符串替换成变量的拼接能力,当然,模板字符串不仅仅如此。

var text = `hello`;
console.log(message);               // "Hello"
console.log(typeof message);        // "string"
console.log(message.length);        // 5

拼接可包含html标签

       let data = [
            {title: '我是1号新闻', read: 1},
            {title: '我是2号新闻', read: 2},
            {title: '我是3号新闻', read: 3},
            {title: '我是4号新闻', read: 4},
            {title: '我是5号新闻', read: 5}
        ]

        window.onload = function() {
            var oUl = document.querySelector('ul');

            for(let i=0; i < data.length; i++) {
                var oLi = document.createElement('li');
                oLi.innerHTML = `<span>新闻标题:${data[i].title}</span>
                <span>阅读人数:${data[i].read}</span>
                <a href="javascript:;">详情</a>`
                oUl.appendChild(oLi);
            }
        }

在这里插入图片描述
      当动态添加DOM节点的时候,使用传统字符串拼接(尤其是多行文本的时候),会大篇幅的在拼接处用( '+变量+' )的格式拼接,同时还要改每一行的开头或格式,这个时候就会显得操作很繁琐,而ES6引入模板字符串后,使用反引号将需要添加的内容包起来(单行文本 / 多行文本都一样)然后在变量的地方用 ${变量}的形式替换掉就直接实现了与之前相同的功能,无论从本地或是从后台获取的数据都需要动态添加,那么其中多少都会涉及到字符串拼接,那么抛弃传统的字符串拼接方法,使用ES6模板字符串将会让你事半功倍

通过上述例子,可以看出,其实模板字符串创建的就是普通的字符串,没有什么特别的地方。当然,如果想创建多行的字符串,以前的方法可能是这样:

/* 以前创建多行字符串的方法 */
var text = "hello\nworld";      
console.log(text);              //hello
                                //world
                                
/* 使用模板字符串创建多行字符串的方法 */
var text =`hello\nworld`;    
var text1 =`hello
world`;
console.log(text);              //hello
                                //world
console.log(text1);             //hello
                                //world                               
2.使用模板字符串还有值得注意的几点:
  1. 空格符(空白符)也会占位置:
var text=`hello
                world`;
console.log(text);           //hello
                                //                world
console.log(text.length)     //27
  1. 如果想让\n输出,可以使用转义字符,变为\\n,或者直接使用String.raw:
var text =String.raw`hello\nworld`;
var text1 =`hello\\nworld`;
console.log(text);              //hello\nworld 
console.log(text1);              //hello\nworld 

二、优势

  1. 拼接变量
let myName = "moonburn";
let message = `hello,my name is ${myName}`; //拼接变量
console.log(message)           //"hello,my name is moonburn"



/*变量拼接也可以进行计算:*/
let jiao= 0.1,
 message = `${jiao}角等于${jiao*10}分,也等于${(jiao* 0.1).toFixed(3)}元。`
 
console.log(message)           //"0.1角等于1分,也等于0.010元。"
  1. #拼接模板字符串本身
let myName = "moonburn";
let message = `hello,${`my name is ${myName}`}`;

console.log(message)           //"hello,my name is moonburn"
  1. ES6还出了模板标签(Tagged Templates)
/* 
格式:
let text = sayHello`args`;
function sayHello(){
    //do something
}
*/
let text = sayHello`hello`;
function sayHello(array1,...array2){
   console.log(array1);     //["hello"]
   console.log(array2);     //undefined
   console.log(array3);     //undefined
   return 123;
}
console.log(text)    //123

模板标签可以做什么?

let text = sayHello`hello`;
function sayHello(array1,...array2){
   console.log(array1);     //["hello"]
   console.log(array2);     //undefined
   return 123;
}
console.log(text)    //123

不明白了?嗯,其实这个模板标签也就是sayHello把模板字符串`hello`当做参数(两个参数具体怎么分配,我们下面在探讨),然后经过一系列的计算,最后返回一个字符串return 123,给text,所以最后text的值是123。
下面我们再看一个复杂一点的例子:

let word= "world"
let name = "moonburn"
let text = sayHello`hello ${word},my name is ${name}`;
function sayHello(array1,...array2){
   console.log(array1);     //["hello ",",my name is ",""]
   console.log(array2);     //["world", "moonburn"]
   return 123;
}
console.log(text)    //123

通过这个例子,我们可以明白,函数的第一个参数就是模板字符串中非变量的部分组成的数组,值得注意的是,模板字符串的最开始和最后一定要是普通字符串,如果是变量开始或者结尾,就像上述例子,那么就会有空字符串也就是""出现,通过这一点,我们就可以保证,第一个参数的长度永远比第二个参数长一个单位,也就是说array1.length === array2.length+1恒为true。第二个参数是什么呢?显而易见了,就是变量。那么我们来看看默认的模板标签是怎么样的呢?

let word= "world"
let name = "moonburn"
let text = sayHello`hello ${word},my name is ${name}`;
function sayHello(array1,...array2){
    let result = "";
    for (let i = 0; i < array2.length; i++) {
        result += array1[i];
        result += array2[i];
    }
    //加上最后一个普通字符串。
    result += array1[array1.length - 1];
    return result;
}
console.log(text)    //"hello world,my name is moonburn"

当然,array2的值不仅仅只是字符串,如果是需要计算的数,或者回调函数,那么计算完毕之后再进行模板标签的函数调用。

let word= "world"
let name = function(){
    console.log("函数调用")
    return "moonburn"
}
let text = sayHello`hello ${word},my name is ${name()}`;
function sayHello(array1,...array2){
    let result = "";
    for (let i = 0; i < array2.length; i++) {
        result += array1[i];
        result += array2[i];
    }
    //加上最后一个普通字符串。
    result += array1[array1.length - 1];
    return result;
}
console.log(text)  
 //函数调用
 //"hello world,my name is moonburn"

总结

  • 不带变量的模板字符串就是普通字符串的加强版,换行之类的操作更加方便,注意空格。
  • 带变量的模板字符串可以接受变量计算,函数回调等,最后输出的还是字符串。
  • 模板标签可以自己人性化配置模板字符串,接受2个参数,返回值也是自己定义。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值