String.raw()是一个模板字符串的标签函数,它的作用类似于 Python 中的字符串前缀r和 C# 中的字符串前缀@,是用来获取一个模板字符串的原始字面量值的。
语法
String.raw(callSite, ...substitutions)String.raw`templateString`
参数
callSite一个模板字符串的“调用点对象”。类似{ raw: ['foo', 'bar', 'baz'] }。...substitutions任意个可选的参数,表示任意个内插表达式对应的值。templateString模板字符串。返回
给定模板字符串的原始字面量值。异常
TypeError如果第一个参数没有传入一个格式良好的调用点对象,则会抛出TypeError异常。描述
不要被上面复杂的参数要求吓到,因为像所有的标签函数一样,你通常不需要把它看成一个普通函数,你只需要把它放在模板字符串前面就可以了,而不是在它后面加个括号和一堆参数来调用它,引擎会替你去调用它。String.raw() 是唯一一个内置的模板字符串标签函数,因为它太常用了。不过它并没有什么特殊能力,你自己也可以实现一个和它功能一模一样的标签函数。
示例
console.log(String.raw`Hi\n${2+3}!`);
// 'Hi\n5!', the character after 'Hi'
// is not a newline character,
// '\' and 'n' are two characters.
console.log(String.raw`Hi\u000A!`);
// 'Hi\u000A!', same here, this time we will get the
// \, u, 0, 0, 0, A, 6 characters.
// All kinds of escape characters will be ineffective
// and backslashes will be present in the output string.
// You can confirm this by checking the .length property
// of the string.
let name = 'Bob';
console.log(String.raw`Hi\n${name}!`);
// 'Hi\nBob!', substitutions are processed.
// Normally you would not call String.raw() as a function,
// but to simulate `t${0}e${1}s${2}t` you can do:
console.log(String.raw({ raw: 'test' }, 0, 1, 2)); // 't0e1s2t'
// Note that 'test', a string, is an array-like object
// The following is equivalent to
// `foo${2 + 3}bar${'Java' + 'Script'}baz`
console.log(String.raw({
raw: ['foo', 'bar', 'baz']
}, 2 + 3, 'Java' + 'Script')); // 'foo5barJavaScriptbaz'
网友回复