Removing elements with Array.map in JavaScript

后端 未结 8 2080
无人及你
无人及你 2020-12-08 12:43

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)
{
            


        
8条回答
  •  星月不相逢
    2020-12-08 13:17

    You must note however that the Array.filter is not supported in all browser so, you must to prototyped:

    //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;
        };
    }
    

    And doing so, you can prototype any method you may need.

提交回复
热议问题