javascript 当我返回 `false` 时,为什么 `_.map` 返回 undefined?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20920532/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 19:36:36  来源:igfitidea点击:

Why is `_.map` returning undefined when I return `false`?

javascriptarraysunderscore.js

提问by jhamm

I have a function, which maps an array with underscore. Here is the function:

我有一个函数,它用underscore. 这是函数:

var services = _.map(userCopy.get('services'), function (service) {
    if (service.service_selected === true) {
        return service;
    }
});

My problem is that when the conditional === false, then I get undefinedput into services. Of course I can remove the undefined, but that is ugly and I just want to use mapcorrectly. How do I fix this?

我的问题是,当conditional === false,然后我得到undefined投入services。当然我可以删除undefined,但那很难看,我只想map正确使用。我该如何解决?

回答by thefourtheye

_.mapuses whatever the function returns, to build the result. If a function doesn't return anything explicitly, JavaScript returns undefined. That's why the result of _.maphas undefinedwhenever the condition fails.

_.map使用函数返回的任何内容来构建结果。如果函数没有明确返回任何内容,JavaScript 将返回undefined. 这就是为什么结果_.mapundefined每当条件失败。

What you actually need, is a _.filter

你真正需要的是 _.filter

var services = _.filter(userCopy.get('services'), function(service) {
    return service.service_selected === true;
});

_.filteraccepts a collection and a predicate function. It applies the predicate function to each and every value of the collection and if the function returns true, that element will be included in the result, if the function returns false, that element will be skipped.

_.filter接受一个集合和一个谓词函数。它将谓词函数应用于集合的每个值,如果函数返回true,则该元素将包含在结果中,如果函数返回false,则该元素将被跳过。

Note:You can actually use _.matcher, along with _.filter, like this

注意:您实际上可以像这样_.matcher一起使用, 和_.filter,

var isServiceSelected = _.matcher({
    service_selected: true;
});

var services = _.filter(userCopy.get('services'), isServiceSelected);

This will be very useful if you are going to filter based on service_selected: truecondition more than once. If it is just a one-time thing, then _.whereshown below would be better alternative.

如果您要service_selected: true多次根据条件进行过滤,这将非常有用。如果这只是一次性的事情,那么_.where下面显示的将是更好的选择。



You can also use _.where, which can return the objects only if the current object contains all the key-value pairs listed, like this

您也可以使用_.where,它只有在当前对象包含列出的所有键值对时才能返回对象,就像这样

var services = _.where(userCopy.get('services'), {
    service_selected: true;
});

Now, all the service objects will be returned which have service_selectedattribute value as true.

现在,将返回service_selected属性值为 的所有服务对象true



Demo:

演示:

function display(heading, data) {
    var json = JSON.stringify(data, null, 4);
    document.body.appendChild(document.createElement('h3')).innerHTML = heading;
    document.body.appendChild(document.createElement('pre')).innerHTML = json;
}


var data = [{
    "name": "auth",
    "service_selected": true
}, {
    "name": "authorization",
    "service_selected": false
}, {
    "name": "faltu",
    "service_selected": true
}];


display("_.filter", _.filter(data, function (service) {
    return service.service_selected === true;
}));

display("_.matcher", _.filter(data, _.matcher({
    service_selected: true
})));

display("_.where", _.where(data, {
    service_selected: true
}));
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

回答by Cmag

Updated my answer... This solved my problem

更新了我的答案...这解决了我的问题

    var missingParamsArray = _.map(requiredParams, function (val, param) {
        if (val) {
            if (!req.user[param]) {
                return param;
            }
        }
    });

    var missingParams = _.filter(missingParamsArray, Boolean);

missingParams can also be written as

missingParams 也可以写成

var missingParams = _.filter(missingParamsArray, function (param) {
       return param !== undefined;
    });