How can I skip an array element in .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"]

推荐答案

Just .filter() it first:

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(). You can generally express .map() in terms of .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():

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. The image source is only pushed onto the result array in the case where the filter operation would have kept it.

update — This question gets a lot of attention, and I'd like to add the following clarifying remark. The purpose of .map(), as a concept, is to do exactly what "map" means: transform a list of values into another list of values according to certain rules. Just as a paper map of some country would seem weird if a couple of cities were completely missing, a mapping from one list to another only really makes sense when there's a 1 to 1 set of result values.

I'm not saying that it doesn't make sense to create a new list from an old list with some values excluded. I'm just trying to make clear that .map() has a single simple intention, which is to create a new array of the same length as an old array, only with values formed by a transformation of the old values.

Javascript相关问答推荐

yarn安装一个本地npm包,以便本地包使用main项目的node_modules(ckeditor-duplicated-modules错误)

按下同意按钮与 puppeteer 师

从WooCommerce Checkout Country字段重新排序国家,保持国家同步

如何从一个列表中创建一个2列的表?

如何用拉威尔惯性Vue依赖下拉?

如何从HTML对话框中检索单选项组的值?

如何强制Sphinx中的自定义js/css文件始终加载更改而不缓存?

基于props 类型的不同props ,根据来自接口的值扩展类型

Vaadin定制组件-保持对javascrip变量的访问

try 使用PM2在AWS ubuntu服务器上运行 node 进程时出错

为什么云存储中的文件不能公开使用?

在D3条形图中对具有相同X值的多条记录进行分组

在Vercel中部署Next.js项目时获取`ReferenceError:未定义文档`

React:防止useContext重新渲染整个应用程序或在组件之间共享数据而不重新渲染所有组件

是否设置以JavaScript为背景的画布元素?

为什么我的SoupRequest";被重置为初始值,以及如何修复它?

使用jQuery每隔几秒钟突出显示列表中的不同单词

正在发出错误的URL请求

响应,Use Callback更新状态变量,该变量也存在于其依赖数组中,它如何防止无限重新呈现?

在继续循环之前,请等待带有异步调用的函数完成