還記得我們用到死的for循環嗎 ?
有時候for循環是真的很耗性能不說 , 而且要寫一堆代碼 , 代碼冗余 ..
這里推薦大家幾個特別好用的數組的方法 , 再不用for循環 , 一句話搞定!~~
1.filter()
創建一個新的數組,新數組中的元素是通過檢查指定數組中符合條件的所有元素。
注意?? :
1.filter() 不會對空數組進行檢測。
2.filter() 不會改變原始數組。
array.filter(function(currentValue,index,arr), thisValue)
const arr = [34, 65, 87, 48, 99];
// filter() 方法
const arrNew = arr.filter(num => {
return num >= 66;
});
console.log(arrNew); // [ 87, 99 ]
filter()會幫我們返回數組中所有符合條件的元素.此時不用在for循環了.
2.find()
方法返回通過測試(函數內判斷)的數組的第一個元素的值。
注意?? :
1.find() 對于空數組,函數是不會執行的。
2.find() 并沒有改變數組的原始值。
執行過程如下 :
1.數組中的每個元素都調用一次函數執行
2.當數組中的元素在測試條件時返回 true 時, find() 返回符合條件的元素,之后的值不會再調用執行函數。
3.如果沒有符合條件的元素返回 undefined
array.find(function(currentValue, index, arr),thisValue)
const arr = [34, 65, 87, 48, 99];
// find() 方法
const arrNew = arr.find(num => {
return num >= 66;
});
console.log(arrNew); // 87
所以 , 我們可以總結一下 filter() 和 find():
- 它們對于空數組都不會執行 , 會返回undefined
- 不改變原數組
- 它們的區別就是 filter()方法 會返回所有符合條件的元素 , 并創建一個新數組 ,
但是find()方法只會返回符合條件的一個元素
3.map()
返回一個新數組,數組中的元素為原始數組元素調用函數處理后的值。
注意?? :
1.map() 不會對空數組進行檢測。
2.map() 不會改變原始數組。
array.map(function(currentValue,index,arr), thisValue)
const arr = [1, 3, 4, 5];
const res = arr.map((num)=>{
return num * num;
})
console.log(res) // [ 1, 9, 16, 25 ]
map()方法 返回一個新數組,數組中的元素為原始數組元素調用函數處理后的值。
4.forEach()
用于調用數組的每個元素,并將元素傳遞給回調函數。
注意??:
forEach() 對于空數組是不會執行回調函數的。
array.forEach(function(currentValue, index, arr), thisValue)
const arr = [1, 2, 3, 4]
arr.forEach(val =>{
console.log(val)
}) // 1 2 3 4
所有 forEach()方法可以拿到我們的數組中每一個值 , 也就是我們遍歷數組了 ~