原文鏈接:http://mp.weixin.qq.com/s?__biz=MzI0ODU5Mzg0NA==&mid=2247483659&idx=1&sn=913e99fbc8ee7840c2ee71caa7de5d86&chksm=e99f2dd0dee8a4c6368924a3e392cffb4ae65d635ea6e62479aed6458aac7aaf477aa88e0f65#rd Template Literals(模板對象)
ES6中的模板字符串(Template String)是一種能在字符串文本中內嵌表達式的字符串字面量(String Literal)。 let firstName = 'Zhang', lastName = 'San'; let fullName = `${firstName} ${lastName}`; console.log(fullName); // 輸出:Zhang San let add = function(x, y) { return `${x} + ${y} = ${x + y}`; }; console.log(add(10, 5)); // 輸出:10 + 5 = 15 與普通字符串不同的是,模板字符串可以多行書寫。 console.log(` <div> Support for multiple lines with backticks </div>`); 模板字符串中所有的空格、新行、縮進,都會原樣輸出在生成的字符串中。 Extended Literals(字面量的擴展)ES6增加了兩個新的數字進制標識符,第二個字母為b來表示二進制,第二個字母為o來表示八進制。 console.log(0b111110111 === 503) // 輸出: true console.log(0o767 === 503) // 輸出: true ES6更好的支持Unicode,支持擴展字符串和正則表達式的Unicode。 Enhanced Regular Expression(增強的正則表達式)ES6對正則表達式添加了u修飾符,含義為“Unicode模式”,用來正確處理大于\uFFFF的Unicode字符。也就是說,會正確處理四個字節的UTF-16編碼。 console.log(/^\uD83D/u.test('\uD83D\uDC2A')); // 輸出: true console.log(/^\uD83D/.test('\uD83D\uDC2A')); // 輸出: false 上面的代碼中,\uD83D\uDC2A是一個四字節的UTF-16編碼,代表一個字符。不加“u”,會按 ES5 將其識別為2個字符,加了“u”之后,會按 ES6 將其正確識別為一個字符。 ES6對正則表達式添加了y修飾符,叫做“粘連”(sticky)修飾符。y修飾符的作用與g修飾符類似,也是全局匹配,后一次匹配都從上一次匹配成功的下一個位置開始。不同之處在于,g修飾符只要剩余位置中存在匹配就可,而y修飾符確保匹配必須從剩余的第一個位置開始。 // y修飾符 var s = 'aaa_aa_a'; var r1 = /a+/g; var r2 = /a+/y; // 第一次匹配都成功 console.log(r1.exec(s)[0]); // 輸出: aaa console.log(r2.exec(s)[0]); // 輸出: aaa console.log(r1.exec(s)[0]); // 輸出: aa // 剩余部分第一個位置是下劃線,不匹配 console.log(r2.exec(s)); // 輸出: null ES6 為正則表達式新增了sticky屬性,用于表示正則對象是否設置了y修飾符。 var r = /hello\d/y; console.log(r.sticky); // 輸出: true ES6 為正則表達式新增了flags屬性,返回正則表達式的修飾符。 console.log(/abc/ig.flags); // 輸出: gi Enhanced Object Literals(增強的對象字面量)ES6新增屬性的簡潔表示法,允許直接寫入變量和函數,作為對象的屬性和方法。這樣的書寫更加簡潔。 function f1(x, y) { return { x, y }; } 除了屬性簡寫,ES6方法也可以簡寫。 function f2() { return { hello() { return "Hello!"; } } } ES6新增屬性名表達式,允許字面量定義對象時,用表達式作為對象的屬性名,即把表達式放在方括號內。 function f3() { return { foo: true, ['a' + 'bc']: 123 } } function getCar(make, model, value) { return { make, model, value, ['make' + make]: true, depreciate() { this.value -= 2500; } }; } let car = getCar('Kia', 'Sorento', 40000); console.log(car); // 輸出: Object {make: "Kia", model: "Sorento", value: 40000, makeKia: true} car.depreciate(); console.log(car.value); // 輸出: 37500 Destructuring Assignment(解構賦值)ES6允許按照一定模式,從數組和對象中提取值,對變量進行賦值,這被稱為解構(Destructuring)。 解構賦值允許你使用類似數組或對象字面量的語法將數組和對象的屬性賦給各種變量。這種賦值語法極度簡潔,同時還比傳統的屬性訪問方法更為清晰。 數組的解構賦值,可以從數組中提取值,按照對應位置,對變量賦值。 let numbers = [10, 20]; let [a, b] = numbers; console.log(a, b); // 輸出: 10 20 對象的解構賦值。 let position = { lat: 42.34455, lng: 17.34235 }; let { lat, lng } = position; console.log(lat, lng); // 輸出: 42.34455 17.34235 字符串的解構賦值,字符串被轉換成了一個類似數組的對象。 const [c1, c2, c3, c4, c5] = 'hello'; console.log(c1, c2, c3, c4, c5); // 輸出: h e l l o 函數參數的解構賦值 function add([x, y]) { return x + y; } console.log(add([1, 2])); // 輸出: 3 |