ES6學會這些就夠了
阿新 • • 發佈:2019-01-11
1.變數宣告 const 和 let 在ES6之前,我們都是用 var 關鍵字宣告變數:無論在何處宣告,都會被視為宣告在函式的'最頂部'(不在函式內即在全域性作用域的最頂部)這就是'函式變數提升'; ES6時代,我們通常用 let 和 const 來宣告變數(let 和 const 都是塊級作用域:說白了{}大括號內的程式碼塊即為 let 和 const 的作用域): let 表示變數:let 的作用域是在它所在當前程式碼塊,但不會被提升到當前函式的最頂部。 const 表示常量:const 宣告的變數都會被認為是常量,意思就是它的值被設定完成後就不能再修改了(如果const的是一個物件,物件所包含的值是可以被修改的。抽象一點兒說,就是物件所指向的地址沒有變就行) 2.模板字串 ①字串拼接:將表示式嵌入字串中進行拼接,用${}來界定 //ES5 var name = 'lux' console.log('hello' + name) //es6 這種用途是趨勢,需要熟練掌握 const name = 'lux' console.log(`hello ${name}`) //hello lux ②多行字串原樣輸出用反引號(``) const template = ` <div> <span>hello world</span> </div>` ③處理字串幾個常用的方法: // 1.includes:判斷是否包含然後直接返回布林值 const str = 'hahay' console.log(str.includes('y')) // true // 2.repeat: 獲取字串重複n次 const str = 'he' console.log(str.repeat(3)) // 'hehehe' //如果你帶入小數, Math.floor(num) 來處理 // s.repeat(3.1) 或者 s.repeat(3.9) 都當做成 s.repeat(3) 來處理 // 3. startsWith 和 endsWith 判斷是否以 給定文字 開始或者結束 const str = 'hello world!' console.log(str.startsWith('hello')) // true console.log(str.endsWith('!')) // true 3.函式 ①函式預設引數:在定義函式時給引數一個初始值,以便在引數沒有被傳遞進去時使用。 ②箭頭函式:箭頭函式最直觀的三個特點: (1)不需要 function 關鍵字來建立函式 (2)省略 return 關鍵字 (3)繼承當前上下文的 this 關鍵字 //例如: [1,2,3].map(x => x + 1) //等同於: [1,2,3].map((function(x){ return x + 1 }).bind(this)) 當你的函式有且僅有一個引數的時候,是可以省略掉括號的。當你函式返回有且僅有一個表示式的時候可以省略{} 和 return;例如: var people = name => 'hello' + name //引數name就沒有括號 4.更方便的資料訪問--解構 ①ES5我們提取物件中的資訊方法如下: const people = { name: 'lux', age: 20 } const name = people.name const age = people.age console.log(name + ' --- ' + age) ②在ES6之前我們就是這樣獲取物件資訊的,一個一個獲取。現在,解構能讓我們從物件或者數組裡取出資料存為變數: //物件 const people = { name: 'lux', age: 20 } const { name, age } = people console.log(`${name} --- ${age}`) //陣列 const color = ['red', 'blue'] const [first, second] = color console.log(first) //'red' console.log(second) //'blue' 5.Spread Operator 展開運算子,三個點(...) ①組裝物件或者陣列 //陣列 const color = ['red', 'yellow'] const colorful = [...color, 'green', 'pink'] console.log(colorful) //[red, yellow, green, pink] //物件 const alp = { fist: 'a', second: 'b'} const alphabets = { ...alp, third: 'c' } console.log(alphabets) //{ "fist": "a", "second": "b", "third": "c" ②獲取陣列或者物件除了前幾項或者除了某幾項的其他項 //陣列 const number = [1,2,3,4,5] const [first, ...rest] = number console.log(rest) //2,3,4,5 //物件 const user = { username: 'lux', gender: 'female', age: 19, address: 'peking' } const { username, ...rest } = user console.log(rest) //{"address": "peking", "age": 19, "gender": "female" 對於 Object 而言,還可以用於組合成新的 Object 當然如果有重複的屬性名,下邊覆蓋上邊 const first = { a: 1, b: 2, c: 6, } const second = { c: 3, d: 4 } const total = { ...first, ...second } console.log(total) // { a: 1, b: 2, c: 3, d: 4 }