ES6


Posted by ericcch24 on 2020-10-16

變數宣告:let 與 const

  • const: 常數,設定的變數內容不會改變的時候用,例如: pi = 3.14
  • letvar 的差別:兩者的作用域 (scope) 不同,也就是變數的生存範圍不同
    • var 的生存範圍限於 function 裡面(其他語言較少見)
    • let 範圍則更小,只限於一個區塊 block 內,const範圍亦同,scope 會希望越小越好,因為比較不會干擾到其他變數
function test() {
  if (10 > 5) {
    var a = 10 // 生存範圍為整個函式
  }
  console.log(a) 
}
test() // output: 10

如果 var 改 let,外層的 console.log 就讀不到變數 a

function test() {
  if (10 > 5) {
    let a = 10 // 生存範圍侷限於 if 條件內
  }
  console.log(a) 
}
test() // output: a is not defined

Template Literals

使用方式

  • 多行字串:
    let str = `yo
    man
    sup
    `
    console.log(str) 
    /* 
    output:  
    yo
    man
    sup
    */
    
  • 字串拼接模板:${} 裡面可以放變數、回傳值或程式碼等等,其他放直接輸出的字串,外面用 `` 包住
    function sayHi(name) {
    console.log('hello, ' + name + ' now is ' + new Date())
    console.log(`hello, ${name} now is ${new Date()}`) //ES6 Template Literals
    }
    sayHi('Eric')
    

Spread Operator 展開


Destructuring:解構

  • 陣列
    const arr = [1, 2, 3, 4,]
    let [first, second, third, fourth] = arr
    // 把本來的 arr 解構成我宣告的變數,位置有分別對應
    //let [first, second] = arr 不用全部也可以
    console.log(first) // output: 1
    
  • 物件
    const obj = {
    name: 'eric',
    age: '27',
    address: 'Taiwan'
    }
    let {name, age, address} = obj 
    // 此時 name, age, address 皆為變數,名稱要上面的設定的名稱相同,不然會讀不到
    console.log(address) // output: Taiwan
    

箭頭函式 arrow function

  • 簡單來說就是可以不用打 function 變箭頭跟省略括弧
    ```javascript=
    //原寫法
    function test(n){
    return n
    }

// 箭頭函式
const test = n => {
return n
}

![](https://i.imgur.com/QEjYs2t.png)

```javascript=
arr
  .filter(value => {
    .... //做更多事的時候不要省略大括號
    ..
    ..
    return value > 1
  })

tags: Week3

#week3







Related Posts

AI輔導室|快速完成網格繪製

AI輔導室|快速完成網格繪製

1251. Average Selling Price

1251. Average Selling Price

Java 學習筆記 01 – 開發環境

Java 學習筆記 01 – 開發環境


Comments