admin管理员组

文章数量:1297062

Is this acceptable practice to cast find results to boolean. As I'm new to JS I'm unsure if there are any gotchas. This currently works, but is it acceptable and is there a better practice?

        collection.contains = function collectionHas(name, value, key) {
            key = _.isString(key) ? key : 'app_id';
            if (_.has(store, name)) {
                return !!_.find(store[name], function(item, k) {
                    return item[key] == value;
                });
            }
        };

Is this acceptable practice to cast find results to boolean. As I'm new to JS I'm unsure if there are any gotchas. This currently works, but is it acceptable and is there a better practice?

        collection.contains = function collectionHas(name, value, key) {
            key = _.isString(key) ? key : 'app_id';
            if (_.has(store, name)) {
                return !!_.find(store[name], function(item, k) {
                    return item[key] == value;
                });
            }
        };
Share Improve this question asked Dec 27, 2015 at 21:40 NolanNolan 9161 gold badge7 silver badges20 bronze badges 0
Add a ment  | 

2 Answers 2

Reset to default 8

Use _.some, it works exactly like find but returns a boolean

No you shouldn't directly cast the result of a find operation to a boolean. For example, if you are searching an array for the number 0, then on success the returned value will be 0 which is coerced into the boolean false. Learn more about type coercion in JavaScript here.

You should thus use the === operator to do a strict parison against undefined, which is what _.find returns when it doesn't find anything. From the lodash docs:

Returns (*): Returns the matched element, else undefined.

So your code would bee:

    collection.contains = function collectionHas(name, value, key) {
        key = _.isString(key) ? key : 'app_id';
        if (_.has(store, name)) {
            return undefined !== _.find(store[name], function(item, k) {
                return item[key] == value;
            });
        }
    };

本文标签: Javascript amp lodashcast find result to booleanStack Overflow