在JavaScript中使用Array.map删除元素

时间:2020-03-05 18:39:16  来源:igfitidea点击:

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

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

问题在于,过滤掉的项目仍会使用数组中的空间,我想彻底清除它们。

任何的想法?

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

EDIT2:感谢指出并非所有浏览器都实现了map()和filter(),尽管我的特定代码并非旨在在浏览器中运行。

解决方案

回答

那不是地图的作用。我们真的想要Array.filter。或者,如果我们确实要从原始列表中删除元素,则需要使用for循环来强制执行此操作。

回答

除非要过滤,否则我们应该使用filter方法而不是map,除非我们想对数组中的项目进行突变。

例如。

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

[编辑:当然,我们总是可以执行sourceArray.filter(...)。map(...)来进行过滤和变异]

回答

但是,我们必须注意,并非所有浏览器都支持Array.filter,因此必须原型化:

//This prototype is provided by the Mozilla foundation and
//is distributed under the MIT license.
//http://www.ibiblio.org/pub/Linux/LICENSES/mit.license

if (!Array.prototype.filter)
{
    Array.prototype.filter = function(fun /*, thisp*/)
    {
        var len = this.length;

        if (typeof fun != "function")
            throw new TypeError();

        var res = new Array();
        var thisp = arguments[1];

        for (var i = 0; i < len; i++)
        {
            if (i in this)
            {
                var val = this[i]; // in case fun mutates this

                if (fun.call(thisp, val, i, this))
                   res.push(val);
            }
        }

        return res;
    };
}

这样,我们就可以原型化我们可能需要的任何方法。

回答

var arr = [1,2,'xxx','yyy']

arr = arr.filter(function(e){ return e != 'xxx' });

arr  // [1, 2, "yyy"]