How to skip over an element in .map()?

前端 未结 16 2026
余生分开走
余生分开走 2020-11-27 09:26

How can I skip an array element in .map?

My code:

var sources = images.map(function (img) {
    if(img.src.split(\'.\').pop() === \"json         


        
16条回答
  •  隐瞒了意图╮
    2020-11-27 10:02

    Since 2019, Array.prototype.flatMap is a good option.

    images.flatMap(({src}) => src.endsWith('.json') ? [] : src);
    

    From MDN:

    flatMap can be used as a way to add and remove items (modify the number of items) during a map. In other words, it allows you to map many items to many items (by handling each input item separately), rather than always one-to-one. In this sense, it works like the opposite of filter. Simply return a 1-element array to keep the item, a multiple-element array to add items, or a 0-element array to remove the item.

提交回复
热议问题