Why does javascript map function return undefined?

前端 未结 7 1278
梦谈多话
梦谈多话 2020-12-07 16:24

My code

 var arr = [\'a\',\'b\',1];
 var results = arr.map(function(item){
                if(typeof item ===\'string\'){return item;}  
               });
<         


        
7条回答
  •  抹茶落季
    2020-12-07 16:51

    My solution would be to use filter after the map.

    This should support every JS data type.

    example:

    const notUndefined = anyValue => typeof anyValue !== 'undefined'    
    const noUndefinedList = someList
              .map(// mapping condition)
              .filter(notUndefined); // by doing this, 
                          //you can ensure what's returned is not undefined
    

提交回复
热议问题