1.箭頭函數:
在ES6以前,寫函數表達式的格式爲:
var a = function b(){
console.log('hello')
}
a() //"hello"
ES6中出現了箭頭函數,簡寫了代碼,格式爲:
var a = () => { //()中爲參數
console.log('world')
}
a() //"world" 注:箭頭函數如果不寫成函數表達的形式的話,會報錯
箭頭函數與普通函數的區別:
(1)箭頭函數中的 this 指向的對象是 window(全局);普通函數中的this指向的是本身;
(2)在普通函數中使用 arguments 可以輸出所有參數;但在箭頭函數中使用 arguments 就會報錯;例:
var obj = function(a,b,c,d){
console.log(arguments)
}
obj(1,2,3,4) //輸出全部參數
var test = (a,b,c,d) =>{
console.log(arguments)
}
test(1,2,3,4) //直接報錯
2.for in 循環 和 for of 循環:
在ES6以前,一般用 for in 語句循環對象;
var json = {
'a' : 'banana',
'b' : 'apple',
'c' : 'orange',
'd' : 'peach'
}
for(var i in json){
console.log(json[i]) //依次輸出這個對象所有的值
}
在ES6中用 for of 語句不可以循環對象(它主要用於循環Map對象,也可以循環generator函數);但是可以循環數組,並且相比 for 循環也簡寫了代碼;
var arr = [1,2,3,4]
for (var i of arr){
console.log(i) //直接依次輸出數組中的值
}
3.簡單的信息提取--解構:
在ES6以前,獲取對象或者數組的信息時,需要一條一條的獲取:
var cat = {
key : "hello",
value : "world",
}
var a = cat.key;
var b = cat.value;
console.log(a + '---' +b) //"hello---world"
在ES6中,新增瞭解構,這是將一個數據結構分解爲更小的部分的過程(以上面cat對象爲例):
var {key,value} = cat;
console.log(`${key}---${value}`) //"hello---world"
//再看數組的解構
var rel = [1,2,3];
var [a,b,c] = rel;
console.log(a,b,c) //1 2 3
4.Spread Operator -- 展開運算符,也就是三個點兒(...):
(1)可以對數組或者對象進行淺克隆:
var arr = [1,2,3,4,5];
var arr1 = [...arr];
console.log(arr1); //[1, 2, 3, 4, 5]
//也可以利用解構的方式
var [...get] = arr;
console.log(get); //[1, 2, 3, 4, 5]
(2)可以獲取數組或對象中的某個值或者某幾個值:
//數組
var arr = [1,2,3,4,5];
var [,,...get] = arr; //逗號僅表示數組中的元素
console.log(get) // [3, 4, 5]
//對象
var obj = {
name : 'jack',
age : 22,
}
var {name,...set} = obj; //不同於數組,必須要寫上屬性名
console.log(set) //{age: 22}
(3)對於多個對象,可以創建一個新的對象,將它們整合在一塊兒;
var first = {
a : 1,
b : 2,
}
var two = {
b : 3,
c : 4,
}
var bond = {...first,...two};
console.log(bond) //{a: 1, b: 3, c: 4} ,結果表示:如果遇到重複的屬性名,右邊會覆蓋左邊
5.生成器 -- generator 函數:
特點:比普通函數多了一個*號,在其函數體內要使用yield關鍵定義屬性值;並且函數執行時會在每個yield之後暫停執行;
//普通函數
function test(){
console.log('apple');
console.log('banana')
}
test() //輸出"apple" "banana"
//generator 函數
function* test(){
yield "apple";
yield "banana";
yield "orange";
}
test() //沒有任何輸出值,說明這種方式不可行,必須要使用next(),而且要一條一條的輸出;
var res = test();
console.log(res.next()); //{value: "apple", done: false} 如果想要獲取值,直接res.next().value即可
console.log(res.next()); //{value: "banana", done: false}
console.log(res.next()); //{value: "orange", done: false}
console.log(res.next()); //{value: undefined, done: true}
從中可以看出 next 方法不僅是返回值,而且會返回出一個對象,這個對象擁有兩個屬性:value 和 done;
value 是要獲取的函數中的屬性值;done表示 generator 函數是否已經停止提供值,沒有停止返回false,停止則返回true;