傳入變數以外內容
由於樣板字面值是回傳表達式的值,所以除了變數外,還可寫入函式甚或是另一個樣板字面值
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| const person = { name: '小明', cash: 1000 }; const sentence = `我是${ person.name },身上帶有${ person.cash || 2000 }元`; const sentence_2 = `我是${ person.name },身上帶有${ (function(c) { return c * 2 })(person.cash) }元`; const sentence_3 = `我是${ person.name },身上帶有${ ((c) => c * 2 )(person.cash) }元`; console.log('sentence =>', sentence); console.log('sentence_2 =>', sentence_2); console.log('sentence_3 =>', sentence_3);
const sentence_4 = `我是${ person.name },${ `身上帶有 ${ person.cash }` }元`; console.log('sentence_4 =>', sentence_4);
|
樣板字面值與迴圈搭配
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| const people = [ { name: '小明', cash: 50, }, { name: '阿姨', cash: 100, }, { name: 'Cloud', cash: 1000, }, ];
const list_string = `<ul> ${ people.map((person) => `<li>我是${ person.name },身上有 ${ person.cash } 元</li>`)} </ul> ` console.log('list_string =>', list_string);
const list_string_finish = `<ul> ${ people.map((person) => `<li>我是${ person.name },身上有 ${ person.cash } 元</li>`).join('') } </ul> ` console.log('list_string =>', list_string_finish);
|
參考資料
六角學院 - JavaScript 核心篇