javasript 標籤函數

javasript 標籤函數

說實話javasript 標籤函數使用的場景仍是比較少的,以致於某個同窗問到我這個問題時就懵逼了!!java

什麼是標籤函數

標籤函數的語法是函數名後面直接帶一個模板字符串,並從模板字符串中的插值表達式中獲取參數數組

舉個例子:函數

let a = 5;
let b = 10;

function tag(s, v1, v2) {

    console.log('begin----------');
    console.log(s[0]);
    console.log(s[1]);
    console.log(s[2]);

    console.log(v1);
    console.log(v2);
}


tag`hello ${a + b}  word ${a*b}` //標籤函數1
tag`hello 12 word` //標籤函數1

通常而言,咱們調用函數是這樣的 tag(hello ${a + b} word ${a*b}) 有沒有發現區別?沒錯!!標籤函數是後面直接跟模版字符串,而函數調用是有()的,裏面是參數。好比tag(「參數1」)code

進一步理解ip

tag`hello ${a + b}  word ${a*b}` //標籤函數1
tag`hello 12 word` //標籤函數1
tag"hello asdf asdfg"// 錯誤語句
tag(`hello ${a + b}  word ${a*b}`)//常規的函數調用
tag("hello word")//常規的函數調用

第一個、第二個後面跟的是標籤字符串,因此爲標籤函數,第三個後面的字符串是用""號的,並非標籤語句,語句錯誤。可能到這裏某些同窗還不是很好理解,由於他不知道什麼是模板字符串,下面我介紹模板字符串,看完後可返回在看一下這一塊就很好理解了字符串

模板字符串

模板字符串也是字符串。 只是通常的字符串沒辦法在字符串裏面使用變量或者拼接,模板字符串能夠io

  • 模板字符串語法
  • 在 JavaScript 中編寫字符串時,一般使用 ( ' )或者 ( " ),而模板字符串使用 (`)

普通字符串:console

const str1 ='hello world';
const str2 ="hello world";

模板字符串:function

const str3 =`hello world`;

字符串拼接模板

  • 模板字符串寫法能夠直接使用 ${value} 嵌入表達式:

    let a = 5;
      let b = 10;
      let str = `hello ${a} word ${a + b}`
      console.log(str);
    
      hello 5 word 15 //輸出結果

這裏能夠明顯看出模板字符串的優點,很方便對字符串進行處理

標籤函數的就是函數名後面直接帶一個模板字符串

標籤函數參數

let a = 5;
	let b = 10;
	let str = `hello ${a+b} word ${a*b} word`
  • 第一個參數是被嵌入表達式分隔的文本的數組

    在上面標籤函數被分割的文本數組爲['hello','word', 'word']

  • 第二個參數開始是嵌入表達式的內容

    在上面標籤函數開始是嵌入表達式的內容爲 ${a + b} ${a*b}

  • 下面是輸出例子

    let a = 5;
      let b = 10;
    
    
      function tag(...args) {
          console.log(args);
    
      }
    
    
      tag`hello${a + b}word${a*b}`;
      tag`hello${a + b}`;
      tag`hello${a + b}aaa`;
      tag`hello`;
      tag('我是通常函數');	
    
      /**下面是輸出結果**/
      [ [ 'hello', 'word', '' ], 15, 50 ]
      [ [ 'hello', '' ], 15 ]
      [ [ 'hello', 'aaa' ], 15 ]
      [ [ 'hello' ] ]
      [ '我是通常函數' ]
相關文章
相關標籤/搜索