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

前端 未结 16 2062
余生分开走
余生分开走 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 09:54

    To extrapolate on Felix Kling's comment, you can use .filter() like this:

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

    That will remove falsey values from the array that is returned by .map()

    You could simplify it further like this:

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

    Or even as a one-liner using an arrow function, object destructuring and the && operator:

    var sources = images.map(({ src }) => src.split('.').pop() !== "json" && src).filter(Boolean);
    

提交回复
热议问题