Akh*_*mar 6 javascript google-chrome ecmascript-6 template-strings tagged-templates
我在以下代码中使用标记的模板字符串
var a = 5;
var b = 10;
var pp="";
function tag(strings, ...values) {
pp+=strings[0]; // "Hello "
pp+=strings[1]; // " world "
pp+=values[0]; // 15
pp+=values[1]; // 50
console.log(pp+"Bazinga!");
}
tag`Hello ${ a + b } world ${ a * b}`;
Run Code Online (Sandbox Code Playgroud)
但它给了
未捕获的SyntaxError:意外的令牌......(...)
上 function tag(strings, ...values) {
正如语法错误Unexpected token ...告诉您的那样,问题不是标签,而是剩余运算符的使用。请尝试以下操作:
var a = 5,
b = 10;
function tag(strings) {
var pp="";
pp+=strings[0]; // "Hello "
pp+=strings[1]; // " world "
pp+=arguments[1]; // 15
pp+=arguments[2]; // 50
return pp+"Bazinga!";
}
console.log(tag`Hello ${ a + b } world ${ a * b}`);
Run Code Online (Sandbox Code Playgroud)
根据ES6兼容性表,您需要在当前Chrome中通过harmony标志启用rest语法。