Remove empty elements from an array in Javascript

后端 未结 30 2603
无人共我
无人共我 2020-11-21 09:53

How do I remove empty elements from an array in JavaScript?

Is there a straightforward way, or do I need to loop through it and remove them manually?

30条回答
  •  无人及你
    2020-11-21 10:42

    I'm simply adding my voice to the above “call ES5's Array..filter() with a global constructor” golf-hack, but I suggest using Object instead of String, Boolean, or Number as suggested above.

    Specifically, ES5's filter() already doesn't trigger for undefined elements within the array; so a function that universally returns true, which returns all elements filter() hits, will necessarily only return non-undefined elements:

    > [1,,5,6,772,5,24,5,'abc',function(){},1,5,,3].filter(function(){return true})
    [1, 5, 6, 772, 5, 24, 5, 'abc', function (){}, 1, 5, 3]
    

    However, writing out ...(function(){return true;}) is longer than writing ...(Object); and the return-value of the Object constructor will be, under any circumstances, some sort of object. Unlike the primitive-boxing-constructors suggested above, no possible object-value is falsey, and thus in a boolean setting, Object is a short-hand for function(){return true}.

    > [1,,5,6,772,5,24,5,'abc',function(){},1,5,,3].filter(Object)
    [1, 5, 6, 772, 5, 24, 5, 'abc', function (){}, 1, 5, 3]
    

提交回复
热议问题