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

相关文章
相关标签/搜索