JS中幾種常見的遍歷
-
forEach
forEach是就按照數組或對象中的順序對當前的元素做一些什麼,具體做什麼,隨便
arr[].forEach((item, index, array) => {
// foreach不支持在循環時添加刪除操作,因爲在使用foreach循環的時候數組(集合)就已經被鎖定不能被修改
// 隨便做什麼
// item:當前項,index:當前項的索引, array:原始數組
// 匿名函數中的this 都是指向Window
// 可以沒有返回
})
var ary = [1,2,3,4,5];
var res = ary.forEach((item, index, arr) => {
arr[index] = item * 10;
})
console.log(res) --> undefined
console.log(ary) --> Array (5) [10, 20, 30, 40, 50]
-
filter
filter就像一個過濾器。
例如將數組中大於10的元素放到一個新的數組中,即將數組中的每一項和10做比較,大於10的項放到一個新的數組中。
var temp = [0, 5, 10, 20, 30].filter((item, index) => {
console.log(item); // 數組中的每一項
console.log(index); // 每一項的索引
return item > 10 // 返回大於10的項
})
console.log(temp) --> Array (2) [20, 30]
-
map
即克隆,區別於set。將原始數組中每一項克隆,放到一個新的數組中,結束時,得到一個新的數組,原始數組不變,新數組中的順序和原始數組中一樣
arr[].map((item, index, array) => {
// 針對每一項做點什麼
// item:當前項,index:當前項的索引, array:原始數組
// 可以返回一個對象,用於數組元素轉對象
return XXX // 返回操作後的新項
})
var arr2 = [1,2,3,4,5]
var res2 = arr2.map((item, index, array) => {
return item * 100
})
console.log(res2) --> Array (5) [100, 200, 300, 400, 500] // 原數組拷貝了一份,並進行了修改
console.log(arr2) --> Array (5) [1, 2, 3, 4, 5] // 原數組並未發生變化
// 數組元素轉對象
var arr3 = [1,2,3,4,5]
var obj = arr3.map((item) => ({
key: item,
value: item,
}));
console.log(obj) --> Array (5) [{key: 1}, {key: 2}, {key: 3}, {key: 4}, {key: 5}]
-
Object.keys()
返回對象中每一項的key的數組
var obj = {'0':'a','1':{'key':'1'},'2':10,'3':'xxx'}
var keysArr = Object.keys(obj);
console.log(keysArr); --> Array (4) ['0', '1', '2', '3']
- 結合forEach消除空格
removeBlankSpace = obj => Object.keys(values)
.forEach((key) => {
values[key] = values[key].trim()
}
)
- 結合map獲取對象的值
getValue = obj =>
Object.keys(obj)
.map(key => obj[key])
.join(',')
-
reduce
累加器。從數組中第一項開始,每檢查一項,就和前面的總和加在一起,加到最後返回總和
var temp = [1, 2, 3, 4 ,5].reduce((accumulator, currentValue, currentIndex, array) => {
console.log(accumulator) // 累加器
console.log(currentValue) // 當前項的值
console.log(currentIndex) // 當前項的索引
console.log(array) // 原始數組
return accumulator + currentValue; // 返回所有項的總和
});
console.log(temp) --> Number 15
Set
- ES6 中新的數據結構 Set。它類似於數組,但是成員的值都是唯一的,沒有重複的值。
- Set本身是一個構造函數,用來生成 Set 數據結構。
- 可用通過add()方法向 Set 結構加入成員, Set 結構不會添加重複的值。
- Array.from方法可以將 Set 結構轉爲數組。
const array = [1, 1, 2, 2, 3];
function removeDedupe(array) {
const set = new Set(array)
return Array.from(set);
}
console.log(set) --> Set (3) [1, 2, 3]
console.log(array) --> Array (3) [1, 2, 3]
Set數據結構類似於數組,但成員的值都是唯一的,沒有重複的值。
let set = new Set();
set.add({});
set.size // 1
set.add({});
set.size // 2
Set數據結構中,兩個對象總視爲不相等的(即使爲空)。
-
Set 結構的實例操作方法
- Set.prototype.add(value):添加某個值,返回 Set 結構本身。
- Set.prototype.delete(value):刪除某個值,返回一個布爾值,表示刪除是否成功。
- Set.prototype.has(value):返回一個布爾值,表示該值是否爲Set的成員。
- Set.prototype.clear():清除所有成員,沒有返回值。
-
Set 結構的實例遍歷方法
- Set.prototype.keys():返回鍵名的遍歷器
- Set.prototype.values():返回鍵值的遍歷器
- Set.prototype.entries():返回鍵值對的遍歷器
- Set.prototype.forEach():使用回調函數遍歷每個成員