es6新增的數組方法和對象

es6新增的遍歷數組的方法,後面都會用這個方法來遍歷數組,或者對象,還有set,map

let arr=[1,2,3,4,3,2,1,2];
遍歷數組最簡潔直接的方法法
for (let value of arr) {
    console.log(value);//輸出1,2,3,4,3,2,1,2
}

1. 數組.map()

 

返回一個新的數組,es5要複製一個新的數組咱們通常用循環,如今直接用mapes6

let arr=[1,2,3,4,3,2,1,2];
let newArr=arr.map((value,index,arr)=>value)
console.log(newArr)//輸出[1,2,3,4],固然裏面也能夠返回下標的數組
console.log(newArr==arr)//輸出false

2. 數組.filter()

過濾,返回爲真的值,數組

let arr=[1,2,3,4,3,2,1,2];
let newArr1=arr.filter((value,index,arr)=>value>=3)
console.log(newArr1);//輸出[3,4,3]

3. 數組.reduce()

每一個參數的意思previousValue上次回調的返回值或者初始值,currentValue正在處理的數組值,currentIndex正在處理函數的下標數據結構

//之前找最大值,最小值咱們是用的2層循環來找的,如今直接一行代碼搞定,是否是很爽
let arr=[1,2,3,4,3,2,1,2];
let newArr2=arr.reduce((pre,cur,curIndex,arr)=>pre>cur?pre:cur)
//pre=1不大於cur=2,返回2;
//pre接收返回值2;pre=2不大於cur=3,返回3
.....
//一直找到4而且返回4;
//pre接收4,pre=4大於pre=3而後就一直返回的都是4,這樣就會找到最大值
console.log(newArr2)//輸出4,找到最大值,若是想找最小值只須要pre<cur?pre:cur

es6提供的一種新的數據結構,它相似於數組,可是成員的值都是惟一的,沒有重複的值(包括NaN),可是set內部對象是不相等的

Set不是數組,天然就沒有length屬性,它有size屬性,set.size,就是返回它的成員數量;函數

let set=new Set([1,2,3,4,3,2,1]);//這裏必須傳入的是數組
console.log(set)//輸出set {1,2,3,4}
console.log(set.add(2))//依然輸出set {1,2,3,4}
console.log(set.add(5))//輸出 set {1,2,3,4,5}
console.log(set.delete(1))//輸出true,表示刪除成功
console.log(set.has(2))//輸出true,表示存在這個值
console.log(set.clear())//輸出undefined,這個方法知識刪除全部值,並無返回值
console.log(set)//這時候set已經清空了,因此輸出爲 set {}

Array.from()方法從一個相似數組或能夠迭代的對象中建立一個新的數組實例

let set=new Set([1,2,3,4,3,2,1]);
console.log(Array.from(set))//用這個方法就能夠把set對象轉換我數組,輸出爲[1,2,3,4,3,2,1]
console.log(Array.from('hello'))//輸出爲['h','e','l','l','o']
利用set 和 from達到數組去重
let arr1=[1,2,2,1,1,3,5,2]
console.log(Array.from(new Set(arr1)))//輸出[1,2,3,5],之後別人問你怎麼數組去重,你能夠裝下逼了
寫到這裏忽然想到es6的...方法
console.log([...new Set(arr1)])


Set的遍歷方法
for (let value of set.keys()) {
console.log(value)//輸出鍵
}
for (let value of set.values()) {
console.log(value)//輸出值
}
for (let value of set.entries()) {
console.log(value)//輸出鍵值對
}

es6提供了Map數據結構,它相似於對象,也是鍵值對的集合,可是它的強大在於鍵的範圍能夠任何類型的數據;

let map=new Map([["name","張三"],[[1,2,3],18],[{},"男"]])
console.log(map)
console.log(map.set("name","李四"))//輸出 Map { 'name' => '張三', [ 1, 2, 3 ] => 18, {} => '男' }若是沒有這個鍵,就會添加新的鍵值對到後面
console.log(map.get("name"))//輸出李四
console.log(map.delete("name"))//輸出true
console.log(map.clear())//刪除全部鍵值對
相關文章
相關標籤/搜索