我如何在。map中跳过数组元素?
我的代码:
var sources = images.map(function (img) {
if(img.src.split('.').pop() === "json"){ // if extension is .json
return null; // skip
}
else{
return img.src;
}
});
这将返回:
["img.png", null, "img.png"]
这里有一个有趣的解决方案:
/**
* Filter-map. Like map, but skips undefined values.
*
* @param callback
*/
function fmap(callback) {
return this.reduce((accum, ...args) => {
const x = callback(...args);
if(x !== undefined) {
accum.push(x);
}
return accum;
}, []);
}
与绑定操作符一起使用:
[1,2,-1,3]::fmap(x => x > 0 ? x * 2 : undefined); // [2,4,6]