MDN文檔位置:
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/template_strings
首先 ${表達式} 表示嵌套模板中的占位符韧涨。
var a = 5;
var b = 10;
console.log(`Fifteen is ${a + b} and not ${2 * a + b}.`);
// "Fifteen is 15 and not 20."
模板字符串要用反斜號``表示。
帶標簽的模板字符串(使用標簽函數(shù)解析字符串)
標簽函數(shù)的第一個參數(shù)包含一個字符串值的數(shù)組抛猖。其余的參數(shù)與表達式相關。
面試題1:
function getPerInfo(one,two,three) {
console.log(one);
console.log(two);
console.log(three);
}
const person="Tom";
const age =21;
getPerInfo `${person} is ${age} years old`
答案:
第一個參數(shù)為原始字符串的數(shù)組莫瞬,這個數(shù)組中的元素為${ }
分割的字符串子集察皇。注意若${ }
在模板字符串最左和最右,左邊和右邊會多出來一個""
旧蛾。
此外张遭,在第一個這個數(shù)組參數(shù)中有一個raw屬性邓萨,這個屬性保存的是模板字符串的原生字符串(未經(jīng)過特殊字符替換的字符)。
function tag(strings) {
console.log(strings.raw[0]);
}
tag`string text line 1 \n string text line 2`;
// logs "string text line 1 \n string text line 2" ,
// including the two characters '\' and 'n'
面試題 2
console.log(`${(x=>x)('I love')} to program`)
這個(x=>x)('I love')
為立即執(zhí)行函數(shù)菊卷,直接返回'I love'缔恳,于是最后打印 I love to program