ES6 导入了样板文字串 Template literals 是为了增强字串的表示方式,还能直接填入变数与表达式,可以更方便地输出想要的文字组合了。
使用特性
样板文字串需使用反引号标识‵ ‵
包起来表示可以写入多行的字串// 可写入多行的字串$('#list').html(`<ul> <li>first</li> <li>second</li></ul>`);// 等同于$('#list').html( '<ul>\n' + '<li>first</li>\n' + '<li>second</li>\n' + '</ul>');
可以嵌入变数或任何的表达式,需要使用${ }
来嵌入注意: 换行与空白字元都会被保留,可使用字串的trim()
方法来消除// 可以嵌入变数let name = "Bob", time = "today";console.log(`Hello ${name}, how are you ${time}?`);// 'Hello Bob, how are you today?'// 可以嵌入任何表达式,例如函数、加减运算let today = new Date();let text = `The time and date is ${today.toLocaleString()}`;console.log(text);// The time and date is 2018/1/1 下午6:10:10