Just .filter()
it first:(只是.filter()
首先:)
var sources = images.filter(function(img) {
if (img.src.split('.').pop() === "json") {
return false; // skip
}
return true;
}).map(function(img) { return img.src; });
If you don't want to do that, which is not unreasonable since it has some cost, you can use the more general .reduce()
.(如果您不想这样做,因为这样做要花一些钱,这并不是不合理的,则可以使用更通用的.reduce()
。)
You can generally express .map()
in terms of .reduce
:(你通常可以表达.map()
中的条款.reduce
:)
someArray.map(function(element) {
return transform(element);
});
can be written as(可以写成)
someArray.reduce(function(result, element) {
result.push(transform(element));
return result;
}, []);
So if you need to skip elements, you can do that easily with .reduce()
:(因此,如果您需要跳过元素,则可以使用.reduce()
轻松实现:)
var sources = images.reduce(function(result, img) {
if (img.src.split('.').pop() !== "json") {
result.push(img.src);
}
return result;
}, []);
In that version, the code in the .filter()
from the first sample is part of the .reduce()
callback.(在该版本中,第一个示例的.filter()
的代码是.filter()
.reduce()
回调的一部分。)
The image source is only pushed onto the result array in the case where the filter operation would have kept it.(仅在过滤操作可以保留结果的情况下,才将图像源推入结果数组。) 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…