最近進行前端開發時使用到了filter()、forEach()、map()方法,這里介紹一下它們的大致用法:
1、filter()是通過刪選oldArray,來生產newArray的方法
語法:
array.filter(function(value, index, arr),thisValue)
value:必須,代表當前元素,其他四個參數都是可選,index代表當前索引值,arr代表當前的數組,thisValue代表傳遞給函數的值,一般用this值,如果這個參數為空,undefined會傳遞給this值
返回值:返回數組,包含了符合條件的所有元素,如果沒有符合條件的則返回空數組
用法:
var arr = [1,2,3,4,5,6,7];
var ar = arr.filter(function(elem){
return elem>5;
});
console.log(ar);//[6,7]
簡單用法:
var arr = [1,2,3,4,5,6,7];
var ar = arr.filter(elem => {
return elem>5;
});
console.log(ar);//[6,7]
2、forEach()用於遍歷數組中的每個元素,並將元素傳遞給回調函數。它沒有返回值,直接修改原數組中的數據。跟for循環用法類似。
語法:
array.forEach(function(value, index, arr),thisValue)
value:必須,代表當前元素,其他四個參數都是可選,index代表當前索引值,arr代表當前的數組,thisValue代表傳遞給函數的值,一般用this值,如果這個參數為空,undefined會傳遞給this值。
用法:
let arr = [
{ name: '1',
id: '1'
},{ name: '2',
id: '2'
},{ name: '3',
id: '3'
}
]
arr.forEach(item=>{
if(item.name==='2'){
item.name = 'zding'
}
})
console.log(arr)
[
{ name: '1',
id: '1'
},{ name: 'zding',
id: '2'
},{ name: '3',
id: '3'
}
]
它沒有產生新的數組,修改的是原來的數組。
當數組中為單類型數據時:string、int等類型,這種方式的修改就不起作用了
例如:
let arr = [1,3,5,7,9]
arr.forEach(function(item){
item = 30
})
console.log(arr) //輸出 [1, 3, 5, 7, 9]
我們期望輸輸出 [30, 30, 30, 30, 30],但實際上輸出為 [1, 3, 5, 7, 9],修改沒有起作用。
這個時候我們可以使用for循環,或者map()方法。
map()返回一個新數組,數組中的元素為原始數組元素調用函數處理后的值,map()方法按照原始數組元素順序依次處理元素.
語法:
array.map(function(value, index, arr),thisValue)
用法:
var arr = [1,2,3,4,5,6,7];
var ar = arr.map(function(elem){
return elem*4;
});
console.log(ar);//[4, 8, 12, 16, 20, 24, 28]
console.log(arr);//[1,2,3,4,5,6,7]