模板字符串
ES6中,JS现在有了引号拼接字符串的替代品,模板字符串。
示例: 普通字符串
var firstName = 'Jake';
var lastName = 'Rawr';
console.log('My name is ' + firstName + ' ' + lastName);
// My name is Jake Rawr
模板字符串
var firstName = 'Jake';
var lastName = 'Rawr';
console.log(`My name is ${firstName} ${lastName}`);
// My name is Jake Rawr
在模板字符串中,你可以不用\n
来生成多行字符串,在${}
里做简单的逻辑运算(例如 2+3)甚至使用逻辑运算符。
var val1 = 1, val2 = 2;
console.log(`${val1} is ${val1 < val2 ? 'less than': 'greater than'} ${val2}`)
// 1 is less than 2
你也可以使用函数修改末班字符串的输出内容;这被称为带标签的模板字符串,其中包含了带标签的模板字符串的示例.
或许你还想阅读更多内容来了解模板字符串。
MEET THE NEW JSTIPS BOOK
You no longer need 10+ years of experience to get your dream job.
Use the 100 answers in this short book to boost your confidence and skills to ace the interviews at your favorite companies like Twitter, Google and Netflix.
GET THE BOOK NOW
MEET THE NEW JSTIPS BOOK
The book to ace the JavaScript Interview.
A short book with 100 answers designed to boost your knowledge and help you ace the technical interview within a few days.
GET THE BOOK NOW