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
2 Answers
Reset to default 8Use _.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
版权声明:本文标题:Javascript & lodash ... cast _.find result to boolean - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741616939a2388577.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论