js 數組遍歷map踩坑


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

 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的條件,循環中不會直接跳出循環;

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由於不能返回結果,所以直接返回undefined

所以我們想要map或者forEach進行數據篩選時候不能直接拿到結果,所以我們需要另外一個數組arr3

 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' ]

最好在循環時候把想要的數據拿出來,而不是循環完之后拿出來自己想要的數據

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM