ECMAScript 6(ES6) 特性概覽和與ES5的比較5-文字模板
阿新 • • 發佈:2018-12-20
1.字串插值
單行和多行字串的直觀表示式插值。 (注意:不要混淆,模板文字最初在ECMAScript 6語言規範草案中命名為“模板字串”) ECMAScript 6
var customer = { name: "Foo"} var card = { amount: 7, product: "Bar", unitprice: 42} var message = `Hello ${customer.name}, want to buy ${car.amount} ${card.product} for a total of ${card.amount * card.unitprice} bucks ?` //前後結尾的是右上頓號` 鍵盤tab上面的按鍵,不是單引號',換行不需要換行符
ECMAScript 5
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?";
2.自定義插值
任意方法的靈活表達插值 ECMAScript 6
get`http://example.com/foo?bar=${bar + baz}&quux=${quux}
ECMAScript 5
get(["http://example.com/foo?bar=", "&quux=", ""],bar + baz, quux);
3.原始字串訪問
訪問原始模板字串內容(不解釋反斜槓)。(看不懂) ECMAScript 6
function quux (strings, ...values) { strings[0] === "foo\n" strings[1] === "bar" strings.raw[0] === "foo\\n" strings.raw[1] === "bar" values[0] === 42 } quux`foo\n${ 42 }bar` String.raw`foo\n${ 42 }bar` === "foo\\n42bar"
ECMAScript 5
//ES5中沒有對應的表達方式