为什么javascript map函数返回undefined?


115

我的密码

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

得到以下结果

["a","b",undefined]

我不想在results数组中定义undefined,该怎么办?


3
因为除非字符串,否则您什么也不返回。因此,最后一项返回undefined。如果不是字符串,您期望返回什么?空字符串?
BenM

2
@BenM如果不是字符串,我什么也不想返回。甚至没有定义。
Akshat Jiwan Sharma

4
看来我使用了错误的方法来执行此操作。
Akshat Jiwan Sharma

您可能需要接受答案。
Ikke 2013年

3
jQuery.map实际上足够聪明,不会在结果数组中包含未定义和null值。
唐纳德·泰勒

Answers:


180

如果项目不是字符串,则不返回任何内容。在这种情况下,该函数将返回未定义,即您在结果中看到的内容。

map函数用于将一个值映射到另一个值,但看起来您实际上是要过滤数组,而map函数不适合该数组。

您真正想要的是一个过滤器功能。它需要一个函数,该函数根据您是否希望结果数组中的项目返回true或false。

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

2
啊...我不知道有过滤功能。谢谢。
Akshat Jiwan Sharma

这很有道理。我不是.map'ing我是.filter'ing ...你怎么知道的?哦,谢谢^。^
DigitalDesignDj

非常合乎逻辑的感谢@Ikke
Malik Khalil

节省了我寻找答案的精力。谢谢。
苏菲·张

22

过滤器适用于这种特殊情况,即项目没有被修改。但是在许多情况下,当您使用地图时,您想要对传递的项目进行一些修改。

如果这是您的意图,则可以使用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
}, [])

1
谢谢- map结果与数组undefinedfilter是否返回项目。这是完美的
Zach Smith


10

我的解决方案是在地图后使用过滤器。

这应该支持每种JS数据类型。

例:

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

8

仅当当前元素为时,才返回一个值string。也许分配一个空字符串就足够了:

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

当然,如果要过滤任何非字符串元素,则不应使用map()。相反,您应该研究使用该filter()功能。


3
如果存在数字,则返回空字符串
Prasath K

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

3

您可以像下面的逻辑那样实现。假设您需要一个值数组。

let test = [ {name:'test',lastname:'kumar',age:30},
             {name:'test',lastname:'kumar',age:30},
             {name:'test3',lastname:'kumar',age:47},
             {name:'test',lastname:'kumar',age:28},
             {name:'test4',lastname:'kumar',age:30},
             {name:'test',lastname:'kumar',age:29}]

let result1 = test.map(element => 
              { 
                 if (element.age === 30) 
                 {
                    return element.lastname;
                 }
              }).filter(notUndefined => notUndefined !== undefined);

output : ['kumar','kumar','kumar']
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.