Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ES6 系列之模板字符串 #69

Open
yangtao2o opened this issue Apr 6, 2020 · 0 comments
Open

ES6 系列之模板字符串 #69

yangtao2o opened this issue Apr 6, 2020 · 0 comments

Comments

@yangtao2o
Copy link
Owner

yangtao2o commented Apr 6, 2020

ES6 系列之模板字符串

如果你碰巧要在字符串中使用反撇号,你可以使用反斜杠转义:

let message = `Hello \` World`;
console.log(message); // Hello ` World

值得一提的是,在模板字符串中,空格、缩进、换行都会被保留。

模板字符串支持嵌入变量,只需要将变量名写在 ${} 之中,其实不止变量,任意的 JavaScript 表达式都是可以的。值得一提的是,模板字符串支持嵌套

let arr = [{ value: 1 }, { value: 2 }];
let message = `
  <ul>
    ${arr
      .map(item => {
        return `
        <li>${item.value}</li>
      `;
      })
      .join("")}
  </ul>
`;
console.log(message);

模板标签是一个非常重要的能力,模板字符串可以紧跟在一个函数名后面,该函数将被调用来处理这个模板字符串,举个例子:

let x = "Hi",
  y = "Kevin";
var res = messagefn`${x}, I am ${y}`;
console.log(res);

function messagefn(literals, value1, value2) {
  console.log(literals); // [ "", ", I am ", "" ]
  console.log(value1); // Hi
  console.log(value2); // Kevin
}

原文链接:ES6 系列之模板字符串

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant