es6,es7,es8語法總結 =====>> (不定期更新)
阿新 • • 發佈:2019-01-27
ES6
1. var let const
let,const具有塊級作用域,不具有變數提升
const 用於不能被重新賦值的變數
2. 箭頭函式
我們經常要給回撥函式給一個父級的this
常用辦法就是 var self = this 定義一個變數接住他
使用 箭頭函式,this 將不會受到影響,可以直接用this呼叫父級的this
3. 字串
includes: const string = 'food'; const substring = 'foo'; console.log(string.includes(substring)); 返回的是布林值。 string.repeat(str,count) 如果 string.length < count 即插入str到count == string.length為止
4. 模板字串
const name = 'Tiger';
const age = 13;
console.log(`My cat is named ${name} and is ${age} years old.`);
5.解構
結構陣列:
let [a, b, c, d] = [1, 2, 3, 4];
console.log(a);
console.log(b);
結構物件:
var luke = { occupation: 'jedi', father: 'anakin' }; var occupation = luke.occupation; var father = luke.father; ------------------------------------------------------------- let luke = { occupation: 'jedi', father: 'anakin' }; let {occupation, father} = luke; console.log(occupation); console.log(father);
6.模組
暴露物件:
function sumThree(a, b, c) {
return a + b + c;
}
export { sumThree };
引入:
import { sumThree } from 'math/addition';
7.引數
es6支援設定預設值:
function addTwoNumbers(x=0, y=0) {
return x + y;
}
8.rest引數
處理不定數目引數: function logArguments(...args) { for (let arg of args) { console.log(arg); } }
9.展開操作
可以展示陣列:
Math.max(...[-1, 100, 9001, -32]);
let cities = ['San Francisco', 'Los Angeles'];
let places = ['Miami', ...cities, 'Chicago']; // ['Miami', 'San Francisco', 'Los Angeles', 'Chicago']
10.類
創造類:
class Person {
constructor(name, age, gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
incrementAge() {
this.age += 1;
}
}
11.Maps
可以理解成鍵值對
let map = new Map();
map.set('name', 'david');
map.get('name');
map.has('name');
12.Promises
遠離回撥地獄,可以轉換成垂直程式碼
func1(value1)
.then(func2)
.then(func3)
.then(func4)
.then(func5, value5 => {
});
13.Generators
用同步的程式碼風格來寫非同步程式碼
function* genFunc() {
// (A)
console.log('First');
yield; //(B)
console.log('Second'); //(C)
}
ES7
1. includes
程式碼:
let array = ['1','2','3']
if(array.includes('2')){
console.log('有')
}
2. 指數操作符
2**3 == 8
ES8
1. object.entries()
程式碼:
let obj = {a: 1, b: 2, c: 3};
Object.entries(obj).forEach(([key, value]) =>{
console.log(key + ": " + value); // 輸出a: 1, b: 2, c: 3
})
2.Async Await
非同步看起來和同步寫法一樣
程式碼:
async fetchData(query) =>{
try {
const response = await axios.get(`/q?query=${query}`);
const data = response.data;
return data;
}
catch (error) {
console.log(error)
}
}
fetchData(query).then(data => {
this.props.processfetchedData(data)
})