Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
239 views
in Technique[技术] by (71.8m points)

javascript - 如何跳过.map()中的元素?(How to skip over an element in .map()?)

How can I skip an array element in .map ?(如何跳过.map的数组元素?)

My code:(我的代码:)

var sources = images.map(function (img) {
    if(img.src.split('.').pop() === "json"){ // if extension is .json
        return null; // skip
    }
    else{
        return img.src;
    }
});

This will return:(这将返回:)

["img.png", null, "img.png"]
  ask by Ismail translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.(仅在过滤操作可以保留结果的情况下,才将图像源推入结果数组。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...