Remove empty elements from an array in Javascript

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

    If you've got Javascript 1.6 or later you can use Array.filter using a trivial return true callback function, e.g.:

    arr = arr.filter(function() { return true; });
    

    since .filter automatically skips missing elements in the original array.

    The MDN page linked above also contains a nice error-checking version of filter that can be used in JavaScript interpreters that don't support the official version.

    Note that this will not remove null entries nor entries with an explicit undefined value, but the OP specifically requested "missing" entries.

提交回复
热议问题