Why does javascript map function return undefined?

前端 未结 7 1289
梦谈多话
梦谈多话 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:58

    You only return a value if the current element is a string. Perhaps assigning an empty string otherwise will suffice:

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

    Of course, if you want to filter any non-string elements, you shouldn't use map(). Rather, you should look into using the filter() function.

提交回复
热议问题