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

前端 未结 16 2005
余生分开走
余生分开走 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:03

    I think the most simple way to skip some elements from an array is by using the filter() method.

    By using this method (ES5) and the ES6 syntax you can write your code in one line, and this will return what you want:

    let images = [{src: 'img.png'}, {src: 'j1.json'}, {src: 'img.png'}, {src: 'j2.json'}];
    
    let sources = images.filter(img => img.src.slice(-4) != 'json').map(img => img.src);
    
    console.log(sources);

提交回复
热议问题