Remove empty elements from an array in Javascript

后端 未结 30 2590
无人共我
无人共我 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:37

    If using a library is an option I know underscore.js has a function called compact() http://documentcloud.github.com/underscore/ it also has several other useful functions related to arrays and collections.

    Here is an excerpt from their documentation:

    _.compact(array)

    Returns a copy of the array with all falsy values removed. In JavaScript, false, null, 0, "", undefined and NaN are all falsy.

    _.compact([0, 1, false, 2, '', 3]);

    => [1, 2, 3]

提交回复
热议问题