這部分教程我們主要講解以下幾個常用語法
- 模板字符串
- 帶標簽的模板字符串
- 判斷字符串中是否包含其他字符串
- 給函數設置默認值
模板字符串
- 老式的拼接字符串方法
-
let dessert = '🍰', drink = '🍵' let breakfast = '今天的早餐是 ' + dessert + ' 與 ' + drink + ' !' console.log(breakfast) // 輸出:今天的早餐是 🍰 與 🍵 !
- 模版字符串拼接方法
let dessert = '🍰', drink = '🍵' let breakfast = `今天的早餐是 ${dessert} 與 ${drink} !` console.log(breakfast) // 輸出:今天的早餐是 🍰 與 🍵 !
模板字符串使用方法
- 在變量的周圍添加一組
{}
- 在
{}
左邊添加一個$
- 再用反引號包裹這個字符串
帶標簽的模塊字符串
let dessert = '🍰', drink = '🍵' let breakfast = kitchen`今天的早餐是${dessert} 與 ${drink}!` function kitchen(strings, ...values){ console.log(strings) // 輸出:["今天的早餐是", " 與 ", "!"] console.log(values) // 輸出:["🍰", "🍵"] } breakfast
- strings:是一個數組,元素是模板字符串中的字符串片段
- values:是一個數組, 元素是模塊字符串中使用{}包裹的內容
- 在模塊字符串的前面添加一個標簽,這個標簽處理模塊字符串中的字符和插入的值,這里的標簽是一個函數
判斷字符串中是否包含其它字符串
- startsWith():判斷一個字符串是否以某一個字符串開頭
- endsWith():判斷一個字符串是否以某一個字符串結尾
- includes():判斷一個字符串是否包含某一個字符串
let dessert = '🍰', drink= '🍵' let breakfast = `今天的早餐是 ${ dessert } 與 ${ drink } !` console.log( breakfast .startsWith('今天'), // 輸出:true breakfast .endsWith('!'), // 輸出:true breakfast .includes('早餐是') // 輸出:true )
給函數設置默認值
function breakfast (dessert = '🍰', drink = '🍺') { return `${ dessert }${ drink }` } // 這里 🍰和 🍺是函數breakfast設置的默認參數值,當調用這個函數時沒有給參數時,這時就會使用函數默認的參數值 // 調用函數 breakfast () // 輸出:🍰 🍺 breakfast (🍌, 🍊) // 輸出:🍌 🍊