Why does javascript map function return undefined?

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

    Filter works for this specific case where the items are not modified. But in many cases when you use map you want to make some modification to the items passed.

    if that is your intent, you can use reduce:

    var arr = ['a','b',1];
    var results = arr.reduce((results, item) => {
        if (typeof item === 'string') results.push(modify(item)) // modify is a fictitious function that would apply some change to the items in the array
        return results
    }, [])
    

提交回复
热议问题