樣板字面值 Template Literial

Abby 旦旦
3 min readSep 7, 2021

--

使用反引號 ‵ ‵ 讓字串連接更方便~
在反引號內要插入的值,使用 ${ } 符號~

實例一
取用變數、常數

const cash = 10;
const string = '好生氣啊';
const sentence = `我的 ${ cash } 元掉到了,${ string }`;
console.log(sentence);
-----------------------你也可以使用表達式
const cash = 10;
const string = '';
const sentence = `我的 ${ cash } 元掉到了,${ string || '好生氣啊' }`;
console.log(sentence);
|| 如果string是假值,就會回傳後面的值。

實例二
取用陣列物件的值

const people = [
{
name: '小明',
cash: 50
},
{
name: '阿姨',
cash: 5000
},
{
name: '杰倫',
cash: 10000
}
];
const listString = `<ul>
<li>我是 ${ people[0].name },身上有 ${ people[0].cash }元</li>
<li>我是 XXX,身上有多少元</li>
<li>我是 XXX,身上有多少元</li>
</ul>`;
document.querySelector('#list').innerHTML = listString;

實例三
箭頭函式

const person = {
name: '小明',
cash: 1000
}
const sentence = `我是${person.name},身上帶有 ${((c) => c * 2)(person.cash)} 元`;
console.log(sentence);

(person.cash) 賦予到 參數 c ,因此 1000 * 2。

實例四
巢狀結構 - 在 ${} 裡面再加入樣板字面值 ‵ ‵ ,再加入 ${}

const person = {
name: '小明',
cash: 1000
}
const sentence = `我是${person.name},${ `身上帶有 ${ person.cash }` } 元`;
console.log(sentence);

實例五
使用迴圈

const people = [
{
name: '小明',
cash: 50
},
{
name: '阿姨',
cash: 5000
},
{
name: '杰倫',
cash: 10000
}
];
const listString = `<ul>
${ people.map((person) => `<li>我是 ${person.name},身上
${person.cash } 元</li>`).join('')}
</ul>`;
console.log(listString);
document.querySelector('#list').innerHTML = listString;

實例六
標籤樣板字面值

有機會再查資料。

--

--

Abby 旦旦
Abby 旦旦

Written by Abby 旦旦

從零開始轉職網頁設計,正在緩慢朝前端工程邁進中!偶爾會發一些讀後感和UI分享,ㄚㄚ!

No responses yet