如何跳过.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"]
发布于 2017-02-13 08:12:30
这里有一个有趣的解决方案:
/**
* Filter-map. Like map, but skips undefined values.
*
* @param callback
*/
function fmap(callback) {
return this.reduce((accum, ...args) => {
let x = callback(...args);
if(x !== undefined) {
accum.push(x);
}
return accum;
}, []);
}
与bind operator一起使用
[1,2,-1,3]::fmap(x => x > 0 ? x * 2 : undefined); // [2,4,6]
发布于 2017-10-24 09:32:45
回答sans多余的边缘情况:
const thingsWithoutNulls = things.reduce((acc, thing) => {
if (thing !== null) {
acc.push(thing);
}
return acc;
}, [])
发布于 2018-06-27 17:34:17
为什么不直接使用forEach循环呢?
let arr = ['a', 'b', 'c', 'd', 'e'];
let filtered = [];
arr.forEach(x => {
if (!x.includes('b')) filtered.push(x);
});
console.log(filtered) // filtered === ['a','c','d','e'];
或者更简单地使用filter:
const arr = ['a', 'b', 'c', 'd', 'e'];
const filtered = arr.filter(x => !x.includes('b')); // ['a','c','d','e'];
https://stackoverflow.com/questions/24806772
复制相似问题