在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' ]
最好在循环时候把想要的数据拿出来,而不是循环完之后拿出来自己想要的数据