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個參數,返回值也是自己定義。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章