Removing elements with Array.map in JavaScript

后端 未结 8 2059
无人及你
无人及你 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:07

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

    eg.

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

    [Edit: Of course you could always do sourceArray.filter(...).map(...) to both filter and mutate]

提交回复
热议问题