ES6 - 基本語法 [ lesson 1-3 ]
之前一篇中講到專案構建 但是一般瀏覽器都支援es6了 可以直接測試 所以久不用什麼專案構建 先把語法學完再說
20190228 18:03
今天基本上把活都幹完了 所以才會有一天時間學習 抽空開始學習es6 在後端把介面寫好之前 準備把es6在搞搞清楚
寫java的同學對es一定不陌生 看起來根本就是一個東西
這裡放個連線線上測試ES6程式碼
Lesson 01 let const
var log = function(a){ document.write(a) } function test(){ let a = 2 let a = 2 //報錯 for(let i =0;i<3;i++){ console.log(i) } console.log(i) //報錯 因為塊級作用域 } test() function test_const(){ // const PI; // PI = Math.PI//報錯 const k = { a:1 } k.b = 2 console.log(k) } test_const()
Lesson 02 解構賦值
陣列 物件 字串 函式引數 數值 解構賦值 **類似python的args
20:30到家沒飯吃 繼續寫吧 我看看我能學多久 反正也沒事兒幹
//陣列解構賦值 { let a ,b ,rest; [a,b,c] = [1,2,3] console.log(a,b,c) } { let a,b,c; [a,b,...c] = [1,2,3,4,5,6,7,8,9,0] console.log(a,b,c) } { let a,b; ({a,b} = {a:'first',b:2}) console.log(a,b) } { let a ,b,rest; [a,b,c="default"] = [1,2]// 如果沒有配對的值 就是undefined console.log(a,b,c) } //使用場景 // 1.變數交換 { let a =1 let b =2 // [a,b] = [b,a] // console.log(a,b) } { function f(){ return [1,2] } let a ,b [a,b] = f() console.log(a,b) } // 這個方法很有用啊 好神奇 選擇性的接受某兩個變數 { function f(){ return [1,2,3,4,5,6] } let a,b,c [a,b,,,,c]=f() console.log(a,b,c) // 1 2 6 } // 這兩個場景可以混合使用 { function f(){ return [1,2,3,4,5,6] } let a,b,c [a,b,...c]=f() console.log(a,b,c) // 1 2 [3, 4, 5, 6] } { let a = { p:22, q:true } let {p,q} = a console.log(p,q) //變數名跟key名必須一致 } { let {a=10,b=5} = {a:3} console.log(a,b) //被更改 let } //json物件 這是最常使用到的場景 巢狀 理解好資料結構 { let data = { title:'aili', test:[{ title:'test_aili', desc:'this is a description' }] } let {title:estitle,test:[{title:cntitle}]} = data console.log(estitle,cntitle) //aili test_aili } //剩下的就是函式裡引數的解構賦值
Lesson 03 字串拓展
21:55
安裝babel-polyfill
{ let str = "string" console.log("includes",str.includes("c")) console.log("start",str.startsWith("str")) console.log("end",str.endsWith("ing")) } // 重複 { let str = "aili" console.log(str.repeat(2)) } // 模板字串 這個比較重要 { let name="list" let info = "hello world" let m = `i am ${name},${info}` console.log(m) } { console.log('是個大帥哥'.padStart(9,'aili'))// aili是個大帥哥 就是講後續字串拼接到前面 並且可重複 console.log('是個大帥哥'.padStart(13,'aili'))//ailiaili是個大帥哥 console.log('大帥哥是'.padEnd(8,'aili'))//大帥哥是aili 變相的插入頭尾部 注意位數 } //這個也有點酷炫了 { let user = { name:'aili', info:'hello world!!!!' } a`i am ${user.name},${user.info}` function a(s,v1,v2){ console.log(s,v1,v2)//i am ,,, |aili |hello world!!!! //這個s是個陣列 好驚奇 ["i am ", ",", ""] } } { console.log(String.raw`Hi\n${1+1}`) console.log(`Hi\n${1+1}`) }