在 JavaScript 中使用 Array.map 删除元素 [英] Removing elements with Array.map in JavaScript

查看:36
本文介绍了在 JavaScript 中使用 Array.map 删除元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 map() 函数过滤一组项目.这是一个代码片段:

I would like to filter an array of items by using the map() function. Here is a code snippet:

var filteredItems = items.map(function(item)
{
    if( ...some condition... )
    {
        return item;
    }
});

问题是过滤掉的项目仍然使用数组中的空间,我想完全清除它们.

The problem is that filtered out items still uses space in the array and I would like to completely wipe them out.

有什么想法吗?

谢谢,我忘记了 filter(),我想要的实际上是一个 filter() 然后一个 map().

Thanks, I forgot about filter(), what I wanted is actually a filter() then a map().

感谢您指出 map()filter() 并未在所有浏览器中实现,尽管我的特定代码并不打算在浏览器中运行.

Thanks for pointing that map() and filter() are not implemented in all browsers, although my specific code was not intended to run in a browser.

推荐答案

你应该使用 filter 方法而不是 map 除非你想改变数组中的项目,除了过滤.

You should use the filter method rather than map unless you want to mutate the items in the array, in addition to filtering.

例如

var filteredItems = items.filter(function(item)
{
    return ...some condition...;
});

这篇关于在 JavaScript 中使用 Array.map 删除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆