js---Array物件的常用遍歷方法
阿新 • • 發佈:2018-12-14
1.forEach(),遍歷陣列的每個元素
let arrFor = ['muzi','digbig','muzidigbig','lucky']
//forEach(),遍歷陣列的每個元素
arrFor.forEach((item,index) => {
console.log(`${index}---${item}`)
})
2.map(引數為回撥函式)函式,遍歷陣列每個元素,並回調操作,需要返回值,返回值組成新陣列,原陣列不變;
let arr = [{id:1,name:'muzi'},{id:2,name:'digbig'},{id:3,name:'muzidigbig'},{id:4,name:'lucky'}] const arrMap = arr.map((item,index) => { return { id:item.id, name:item.name, sex:'男' } }) console.log(arrMap)
3.filter(引數為回撥函式)函式:過濾通過條件的元素組成一個新陣列,原陣列不變;
let arr = [{id:1,name:'muzi'},{id:2,name:'digbig'},{id:3,name:'muzidigbig'},{id:4,name:'lucky'}]
const arrFilter = arr.filter((item,index) => {
return item.id >= 2;
})
console.log(arrFilter)
4.some(引數為回撥函式)函式,遍歷陣列中是否有符合條件的函式,返回布林值;
let arr = [{id:1,name:'muzi'},{id:2,name:'digbig'},{id:3,name:'muzidigbig'},{id:4,name:'lucky'}]
const arrSome = arr.some((item,index) => {
return item.id === 5
})
console.log(arrSome)
5.every(引數為回撥函式)函式,遍歷陣列是否每個元素都符合條件,返回布林值;
let arr = [{id:1,name:'muzi'},{id:2,name:'digbig'},{id:3,name:'muzidigbig'},{id:4,name:'lucky'}] const arrEvery = arr.every((item,index) => { return item.id >= 1 }) console.log(arrEvery)
6.find()函式,陣列中的每個元素都執行這個回撥函式;返回第一個滿足條件的元素 之後的元素就不在呼叫;沒有符合的返回undefined;並沒有改變陣列的原始值。
let arr = [{id:1,name:'muzi'},{id:2,name:'digbig'},{id:3,name:'muzidigbig'},{id:4,name:'lucky'}]
const arrFind = arr.find((item,index) => {
return item.id === 1
})
console.log(arrFind)
7.reduce(),合併二維陣列
var twoArr = [['mu','zi'],['dig','big'],['lucky','jiji']];
var oneArr = twoArr.reduce(function(total,currentValue){
// console.log(total)
return total.concat(currentValue);
},[])
console.log(oneArr);//["mu", "zi", "dig", "big", "lucky", "jiji"]