尝试使用标记的模板字符串给出'Uncaught SyntaxError: Unexpected token

Trying to use Tagged template strings gives 'Uncaught SyntaxError: Unexpected token'

本文关键字:Uncaught SyntaxError token Unexpected 字符串      更新时间:2023-09-26

我在下面的代码中使用标记模板字符串

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}`;

但是它给出

Uncaught SyntaxError: Unexpected token…(…)

On function tag(strings, ...values) {

正如语法错误Unexpected token ...告诉您的那样,问题不在于标记,而在于rest操作符的使用。试试以下命令:

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}`);

根据ES6兼容性表,您需要在当前Chrome浏览器中通过harmony标志启用rest语法