js 數組遍歷map踩坑

在react或者vue進行頁面渲染時候,咱們比較喜歡使用map循環遍歷屬性類似的節點,例如列表渲染vue

 1 let res: any[] | JSX.Element[] = []  2     Object.keys(item).forEach((rowItem: any) => {  3       if (rowItem === 'id' || rowItem === 'show' || rowItem === 'text') {  4         return
 5       } else {  6  res.push(  7           <div style={{ paddingBottom: '10px' }}>
 8             <span className="desc-title">{`${item[rowItem].label}:`}</span>
 9             <span className="desc-text">{`${item[rowItem].value}`}</span>
10           </div>,
11  ) 12  } 13     })

咱們在map循環一個數組的時候,在map中加入判斷條件例如item.key = id時候,map不會中斷條件而繼續執行item.key != id的條件,循環中不會直接跳出循環;react

map和foreach都不會跳出循環數組

 1 let arr = [  2   {id:'1',num:'1'},  3   {id:'2',num:'2'},  4   {id:'3',num:'3'},  5 ];  6 let arr1 = arr.map(item=>{  7   if(item.id == 1){  8     return item.id;  9  } 10 }); 11 //[ '1', undefined, undefined ]
12 
13 let arr2 = arr.forEach(item=>{ 14   if(item.id == 1){ 15     return; 16  } 17 }); 18 //undefined

經過上面咱們瞭解到map在條件結束後還會繼續執行循環,出現兩個undefined數據,forEach因爲不能返回結果,因此直接返回undefinedspa

因此咱們想要map或者forEach進行數據篩選時候不能直接拿到結果,因此咱們須要另一個數組arr3code

 1 let arr = [  2   {id:'1',num:'1'},  3   {id:'2',num:'2'},  4   {id:'3',num:'3'},  5 ];  6 let arr1 = [];  7 let arr2 = [];  8 arr.map(item=>{  9   if(item.id == 1){ 10     return; 11   }else{ 12  arr1.push(item.id); 13  } 14 }); 15 [// '2', '3' ]
16 
17 arr.forEach(item=>{ 18   if(item.id == 1){ 19  arr2.push(item.id); 20  } 21 }); 22 //[ '1' ]

最好在循環時候把想要的數據拿出來,而不是循環完以後拿出來本身想要的數據blog

相關文章
相關標籤/搜索