ES6

ES6新語法特性

1.使用let進行變量聲明
function test() {
    if (bool) {
        let test = 'helloworld';
    }
    else {
        //test 在此處訪問不到
        console.log(test);
    }
}
2.常量的聲明
const name = 'zhangsan';
name = 'lisi'; //再次賦值此時會報錯
3.模版字符串
作用一:拼接字符串
//es5
var name = 'lux'
console.log('hello' + name)
//es6
const name = 'zhangsan'
console.log(`hello ${name}`) //hello zhangsan
作用二:多行字符串拼接
//es5
var msg = "Hi \
           man!";
// es6
const template = `<div>
                  <span>hello world</span>
                  </div>`;
4.函數默認參數
//在定義函數時便初始化了這個參數,以便在參數沒有被傳遞進去時使用
function action(num = 200) {
    console.log(num);
}
action(); //200
action(300); //300
5.箭頭函數

箭頭函數特點:

  1. 不需要function關鍵字來創建函數
  2. 省略return關鍵字
  3. 繼承當前上下文的 this 關鍵字
//es5
function test(num1,num2){

}
//es6
(num1,num2)=>{
    
}

//es5
function add(a,b){
    return a+b;
}
//es6
add=(a,b)=>a+b;
6.對象初始化簡寫
//es5
function people(name, age) {
    return {
        name: name,
        age: age
    };
}

//es6
function people(name, age) {
    return {
        name,
        age
    };
}
7.解構
//es5
const people = {
    name: 'zhangsan',
    age: 20
}
const name = people.name;
const age = people.age;
console.log(name + ' ‐‐‐ ' + age);

//es6
const people = {
    name: 'zhangsan',
    age: 20
}
const { name, age } = people;
console.log(`${name} ‐‐‐ ${age}`);
8.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" }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章