为什么javascript map函数返回undefined? [英] Why does javascript map function return undefined?

查看:3022
本文介绍了为什么javascript map函数返回undefined?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码

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

这给出了以下结果

["a","b",undefined]

我不喜欢我不想在结果数组中定义。我怎么能这样做?

I don't want undefined in the results array.How can I do it?

推荐答案

在这种情况下你没有返回任何东西该项目不是字符串。在这种情况下,函数返回undefined,你在结果中看到了什么。

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.

map函数用于将一个值映射到另一个值,但它看起来你真的想要过滤数组,地图函数不适合。

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.

你真正想要的是 filter 功能。根据您是否需要结果数组中的项目,它需要一个返回true或false的函数。

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';  
});

这篇关于为什么javascript map函数返回undefined?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆