Why does javascript map function return undefined?

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

    You aren't returning anything in the case that the item is not a string. In that case, the function returns undefined, what you are seeing in the result.

    The map function is used to map one value to another, but it looks you actually want to filter the array, which a map function is not suitable for.

    What you actually want is a filter function. It takes a function that returns true or false based on whether you want the item in the resulting array or not.

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

提交回复
热议问题