因为对于不匹配的元素,map会返回“undefined”,只返回那些匹配的最佳方法是什么?
let items: string[] = ["false", "false", "true"];
let newItems: string[] = _.map(items, function(item) {
if (item === "true") {
return "newItem";
}
});
console.log(newItems);
// newItems = [undefined,undefined,"newItem"];
let filterItems: string[] = _.filter(items, function(item) {
if (item === "true") {
return "newItem";
}
});
console.log(filterItems);
// filterItems = ["true"]
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
我可以使用_.filter但是过滤器会在需要时返回“true”而不是“newItem”的值。
有什么建议吗?
答案 0 :(得分:2)
您应该filter
然后map
,这样您只需要在匹配项目上调用map
let newItems: string[] = _.map(
_.filter(items, function(item) {
return item === "true";
}),
function(newItem) {
return "newItem";
}
);
答案 1 :(得分:2)
同时使用地图和过滤器:
collection.filter(it => it === 'true').map(it => 'newItem');
如果你不能undefined
一个值,那么返回map
并没有错,但你不想在最终结果中使用filter
,所以只需{{} 1}}然后出去。
您对filter
返回布尔值而非转换值的关注只是过滤器应该如何工作。它返回通过测试函数的原始值,因此您可以在子集上进行映射(或任何其他功能操作)。
答案 2 :(得分:2)
您可以使用reduce同时执行这两项操作:
let items: string[] = ["false", "false", "true"];
let newItems: string[] = _.reduce(items, function(memo, item) {
if (item === "true") {
memo.push("newItem");
}
return memo;
}, []);
let items = ["false", "false", "true"];
let newItems = _.reduce(items, function(memo, item) {
if (item === "true") {
memo.push("newItem");
}
return memo;
}, []);
console.log(newItems);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>