<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>ES6-ES11新特性</title> </head> <body> <script type="text/javascript"> // promise、新增數據結構【基礎數據類型 引用數據類型判斷方法,事件循環、同步異步】 // ES2015-ES6(第6版) // 參考文檔:https://es6.ruanyifeng.com/#docs/intro 涵蓋齊全 // ES2016-ES7(第7版) /* 1.Array.prototype.includes() includes() 方法用來判斷一個數組是否包含一個指定的值,包含則返回 true,否則返回false 2.指數操作符(**) 與Math.pow(..)具有同樣的效果 */ const arr = [1, 2, 3]; console.log(arr.includes(2)); // true console.log(arr.includes(4)); // false console.log(2 ** 10) // 1024 console.log(Math.pow(2, 10)) // 1024 // ES2017-ES8(第8版) /* 1.async await async和await可以像編寫同步代碼一樣編寫異步代碼 解決回調地獄的問題 【await一定要在async中使用】 2.Object.values() 返回一個給定對象的所有可枚舉屬性值的數組 3.Object.entries() 返回一個給定對象自身可遍歷屬性 [key,value] 的數組 4.Object.getOwnPropertyDescriptors() 返回指定對象所有自身屬性的描述對象 5.SharedArrayBuffer對象:SharedArrayBuffer 對象用來表示一個通用的,固定長度的原始二進制數據緩沖區, 類似於 ArrayBuffer 對象,它們都可以用來在共享內存(shared memory)上創建視圖。 與 ArrayBuffer 不同的是,SharedArrayBuffer 不能被分離 語法:new SharedArrayBuffer(length) length:所創建的數組緩沖區的大小,以字節(byte)為單位 6.Atomics對象 提供了一組靜態方法對 SharedArrayBuffer 和 ArrayBuffer 對象進行原子操作 使用文檔參考:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Atomics 7.String padding: padEnd()方法會用一個字符串填充當前字符串(如果需要的話則重復填充),返回填充后達到指定長度的字符串。從當前字符串的末尾(右側)開始填充 語法:str.padEnd(targetLength [, padString]) targetLength:當前字符串需要填充到的目標長度。如果這個數值小於當前字符串的長度,則返回當前字符串本身。 padString 可選 填充字符串。如果字符串太長,使填充后的字符串長度超過了目標長度,則只保留最左側的部分,其他部分會被截斷。此參數的缺省值為 " "(U+0020) padStart() 方法用另一個字符串填充當前字符串(如果需要的話,會重復多次),以便產生的字符串達到給定的長度。從當前字符串的左側開始填充。 語法:str.padStart(targetLength [, padString]) targetLength:當前字符串需要填充到的目標長度。如果這個數值小於當前字符串的長度,則返回當前字符串本身。 padString 可選 填充字符串。如果字符串太長,使填充后的字符串長度超過了目標長度,則只保留最左側的部分,其他部分會被截斷。此參數的默認值為 " "(U+0020)。 */ // 隨着Promise的大規模使用,當.then()過多后,就也會出現類似於回調地獄的情況 --> 解決回調地獄的問題 (async () => { let time = await a1(); time = await a2(time); await a3(time); b1(); b2(); b3(); })(); const obj = { name: 'test', desc: '測試下語法效果', cities: ['北京', '上海', '廣州', '深圳'], course: ['web', 'java', 'node', 'vue', 'react'] } console.log(Object.keys(obj)) // ["name", "desc", "cities", "course"] console.log(Object.values(obj)) // ["test", "測試下語法效果", Array(4), Array(5)] console.log(Object.entries(obj)) // [Array(2), Array(2), Array(2), Array(2)] // 0: (2) ["name", "test"] // 1: (2) ["desc", "測試下語法效果"] // 2: (2) ["cities", Array(4)] // 3: (2) ["course", Array(5)] console.log(Object.getOwnPropertyDescriptors(obj)) // cities: {value: Array(4), writable: true, enumerable: true, configurable: true} // course: {value: Array(5), writable: true, enumerable: true, configurable: true} // desc: {value: "測試下語法效果", writable: true, enumerable: true, configurable: true} // name: {value: "test", writable: true, enumerable: true, configurable: true} const buffer = new SharedArrayBuffer(6); console.log(buffer.byteLength); // 6 const str1 = '測試下填充到一定長度'; console.log(str1.padEnd(25, '哈')); // 測試下填充到一定長度哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈 const str2 = '測試下填充'; console.log(str2.padEnd(8)); // "測試下填充 " const str3 = '66'; console.log(str3.padStart(3, '0')); // 066 const str4 = '2111119211'; const str5 = str4.slice(-4); const numStr = str5.padStart(str4.length, '*'); console.log(numStr) // ******9211 // ES2018-ES9(第9版) /* 1.對象展開:在以前,...只能用來展開數組,但是現在可以用來展開對象了 2.Promise.prototype.finally():在Promise中,如果有不管成功還是失敗都需要執行的語句 3.正則表達式 (1)命名捕獲組 (2)反向斷言 (3)dotAll模式 */ let man1 = { name: "張三", sex: "男" }; let man2 = { name: "小花", sex: "女", age: 22 }; let people = { ...man1, ...man2 }; // 注意:屬性名相同后面的屬性名會覆蓋前面的屬性名 console.log(people); // {name: "小花", sex: "女", age: 22} const str = `<p>百度</p> <p>www.baidu.com</p> `; let reg = /<p>(?<name>.*)<\/p>\s*<p>(?<url>.*)<\/p>/g; const result = reg.exec(str); console.log(result, 'result'); console.log(result.groups.name); // 百度 console.log(result.groups.url); // www.baidu.com const date = '2021-02-25'.match(/(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/) console.log(date) // 分組 年 月 日 const strTest = 'JS5211314你知道么555啦啦啦'; // 正向斷言 const reg1 = /\d+(?=啦)/; const result1 = reg1.exec(strTest); console.log(result1); // 反向斷言 const reg2 = /(?<=么)\d+/; const result2 = reg2.exec(strTest); console.log(result2); // 正則表達式 dotAll 模式 const r = /foo.bar/s // 判斷是否啟用dotAll模式 console.log(r.dotAll) // true console.log(/foo.bar/.test('foo\nbar')); // false console.log(/foo.bar/.test('fooabar')); // true // 使用 dotAll模式匹配 正則表達式中,(.)可以匹配任意字符,但是4個字節的 utf16 和\n \r 換行、回車終止符不能用(.)匹配 console.log(/foo.bar/s.test('foo\nbar')); // true // ES2019-ES10(第10版) /* 1.Object.fromEntries(): 把鍵值對列表轉換為一個對象 Object.fromEntries()方法是Object.entries()的逆操作 2.trimStart()和trimEnd() ES5中有 trim方法用來清除字符串兩邊的空白字符 trimStart() 方法從字符串的開頭刪除空格。trimLeft() 是此方法的別名。 trimEnd()方法從一個字符串的末端移除空白字符。trimRight() 是這個方法的別名 3.Array.prototype.flat(): 默認只會“拉平”一層, 用於將嵌套的數組“拉平”,變成一維的數組。該方法返回一個新數組,對原數據沒有影響; 4.Array.prototype.flatMap(): 對原數組的每個成員執行一個函數(相當於執行Array.prototype.map()) 然后對返回值組成的數組執行flat()方法。該方法返回一個新數組,不改變原數組 5.Function.prototype.toString(): toString() 方法返回一個表示當前函數源代碼的字符串 [次要] 6.String.prototype.matchAll(): matchAll() 方法返回一個包含所有匹配正則表達式的結果及分組捕獲組的迭代器 7.Symbol.prototype.description: description 是一個只讀屬性,它會返回 Symbol 對象的可選描述的字符串 */ const peopleInfo1 = Object.fromEntries([ ['name', 'bob'], ['age', 42] ]) console.log(peopleInfo1) // {name: "bob", age: 42} // 特別適合將 Map 結構轉為對象 const entries = new Map([ ['name', 'sob'], ['age', 29] ]); const peopleInfo2 = Object.fromEntries(entries) console.log(peopleInfo2) // {name: "sob", age: 29} const map = new Map().set('name', 'bala').set('sex', '男'); const peopleInfo3 = Object.fromEntries(map) console.log(peopleInfo3) // {name: "bala", sex: "男"} const emptyStr = ' abc '; console.log("好" + emptyStr.trim() + "看") // "好abc看" ES5 console.log("好" + emptyStr.trimStart() + "看") // "好abc 看" 清除左側空白字符,保留右側空白字符 console.log("好" + emptyStr.trimEnd() + "看") // "好 abc看" 清除右側空白字符,保留左側空白字符 const arr1 = [1, 2, [3, 4]].flat() console.log(arr1, 'arr1') // [1, 2, 3, 4] "arr1" const arr2 = [1, 2, [3, [4, 5]]].flat(2) // [1, 2, 3, 4, 5] "arr2" const arr3 = [1, 2, 3].flatMap((x) => [x, x * 2]) console.log(arr3, 'arr3') // [1, 2, 2, 4, 3, 6] "arr3" const arr4 = [1, 2, 3, 4].flatMap(x => [ [x * 2] ]) console.log(arr4, 'arr4') // [[2], [4], [6], [8]] "arr4" const regexp = /t(e)(st(\d?))/g; const rStr = 'test1test2'; const resStr = [...rStr.matchAll(regexp)]; console.log(resStr[0]); // ["test1", "e", "st1", "1", index: 0, input: "test1test2", groups: undefined] console.log(resStr[1]); // ["test2", "e", "st2", "2", index: 5, input: "test1test2", groups: undefined] console.log(arr2, 'arr2') let sy = Symbol('Symbol數據') console.log(sy.description) // -> Symbol數據 // ES2020-ES11(第11版) /* 1.私有屬性 2.Promise.allSettled() 3.import(): 支持動態加載模塊 4.BigInt(): BigInt 類型的數據必須添加后綴n,BigInt 只用來表示整數,沒有位數的限制,任何位數的整數都可以精確表示 5.globalThis: 全局屬性 globalThis 包含全局的 this 值,類似於全局對象(global object) 6.可選鏈操作符(?.) 7.空值合並運算符(??) */ // 私有屬性和私有方法前面,也可以加上static關鍵字,表示這是一個靜態的私有屬性或私有方法 class Person { name; // 公有屬性 # job; // 私有屬性, 私有屬性,只能在類的內部使用 constructor(name, job) { this.name = name this.#job = job // 符號'#'帶上 } // #getPrviteFun(){ // console.log('私有方法只能內部調用') // } info() { console.log(this.name) console.log(this.#job) // 在內的內部正常訪問私有屬性 // this.getPrviteFun() } } const person = new Person('隔壁老王', '無業游民') console.log(person) // 正常訪問 Person {#job: "無業游民", name: "隔壁老王"} console.log(person.info()) // console.log(person.#job) // 在類的外部無法訪問私有屬性 報錯: Private field '#job' must be declared in an enclosing class // Promise.allSettled()方法接受一組 Promise 實例作為參數,包裝成一個新的 Promise 實例 // 只有等到所有這些參數實例都返回結果,不管是fulfilled還是rejected,包裝實例才會結束 const prmise1 = Promise.resolve(1); const prmise2 = Promise.reject(-1); const allSettledPromise = Promise.allSettled([prmise1, prmise2]); allSettledPromise.then(res => { console.log(res); // [{ status: 'fulfilled', value: 1 },{ status: 'rejected', reason: -1 }] }); // Promise.all()全部成功,才返回成功,有一個失敗就返回失敗 const allPromise = Promise.all([prmise1, prmise2]); allPromise.then(res => { console.log(res); // 報錯 }); // 總結: Promise.all【無法確定所有操作都結束】和 Promise.allSettled 不關心異步操作的結果,只關心這些操作有沒有結束】常用於批量異步任務; // import()也可以用在 async 函數之中 // 注意: 請不要濫用動態導入(只有在必要情況下采用)。靜態框架能更好的初始化依賴,而且更有利於靜態分析工具和 tree shaking 發揮作用 // import('./xx.js').then(module=>{ // import返回promise對象,module就是導入的對象 // module.fn() // fn() xx.js中一個方法 // }) // typeof運算符對於 BigInt 類型的數據返回bigint BigInt 與普通整數是兩種值,它們之間並不相等 // 參考具體api: https://es6.ruanyifeng.com/#docs/number#BigInt-%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B // 超過 53 個二進制位的數值,無法保持精度 console.log(Math.pow(2, 53) === Math.pow(2, 53) + 1) // true // 超過 2 的 1024 次方的數值,無法表示 console.log(Math.pow(2, 1024)) // Infinity const a = 1236589966n; const b = 568965255n; // 普通整數無法保持精度 console.log(Number(a) * Number(b)) // 703576725335631400 // BigInt 可以保持精度 console.log(a * b) // 703576725335631330n console.log(globalThis, typeof globalThis) // Window對象 object // 可選鏈(?.)如果要通過ajax動態獲取數據,但是並不知道后端返回來的數據是否是空值 【最新版谷歌瀏覽器】 const adventurer = { name: 'pig', cat: { name: 'xiaohua' } } const animalName = adventurer.dog ? .name; console.log(animalName); // undefined // 空值合並運算符(??)在JavaScript中很多情況比如空字符串"",0,等等情況,如果用在條件判斷中,都會被認為是false // 可能導致一個問題,就是在使用||運算符時,只需要在左邊的值為 undefined 或者 null 的時候,才返回右邊的值 let aa = 0; let bb = aa || "aaa"; let cc = aa ? ? "aaa"; console.log("bb的值是 " + bb); // bb的值是 aaa console.log("cc的值是 " + cc); // cc的值是 0 </script> </body> </html>
自己整理,請勿隨意轉載!!!!