var name = "Brendan"; console.log(`Yo, ${name}!`);
// => "Yo, Brendan!"
表达式
1 2 3 4 5 6 7 8
var a = 10; var b = 10; console.log(`JavaScript first appeared ${a+b} years ago. Crazy!`);
//=> JavaScript first appeared 20 years ago. Crazy!
console.log(`The number of JS MVC frameworks is ${2 * (a + b)} and not ${10 * (a + b)}.`); //=> The number of JS frameworks is 40 and not 200.
函数
1 2 3
functionfn() { return"I am a result. Rarr"; } console.log(`foo ${fn()} bar`); //=> foo I am a result. Rarr bar.
$() 可以使用任何表达式和方法调用
1 2 3 4 5 6 7 8 9 10
var user = {name: 'Caitlin Potter'}; console.log(`Thanks for getting this into V8, ${user.name.toUpperCase()}.`);
// => "Thanks for getting this into V8, CAITLIN POTTER";
// And another example var thing = 'drugs'; console.log(`Say no to ${thing}. Although if you're talking to ${thing} you may already be on ${thing}.`);
// => Say no to drugs. Although if you're talking to drugs you may already be on drugs.
示例代码:
ES5:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
'use strict';
var customer = { name: "Foo" }; var card = { amount: 7, product: "Bar", unitprice: 42 };
var message = "Hello " + customer.name + ",\n" + "want to buy " + card.amount + " " + card.product + " for\n" + "a total of " + (card.amount * card.unitprice) + " bucks?";
console.log(message);
输出:
Hello Foo, want to buy 7 Bar for a total of294 bucks?
ES6:
1 2 3 4 5 6 7 8 9 10 11
var customer = { name: "Foo" } var card = { amount: 7, product: "Bar", unitprice: 42 } message = `Hello ${customer.name}, want to buy ${card.amount}${card.product} for a total of ${card.amount * card.unitprice} bucks?`
输出:
Hello Foo, want to buy 7 Bar for a total of294 bucks?
let interpreted = 'raw\nstring'; let esaped = 'raw\\nstring'; let raw = String.raw`raw\nstring`; console.log(interpreted); // raw // string console.log(raw === esaped); // true