Remove empty elements from an array in Javascript

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

    'Misusing' the for ... in (object-member) loop. => Only truthy values appear in the body of the loop.

    // --- Example ----------
    var field = [];
    
    field[0] = 'One';
    field[1] = 1;
    field[3] = true;
    field[5] = 43.68;
    field[7] = 'theLastElement';
    // --- Example ----------
    
    var originalLength;
    
    // Store the length of the array.
    originalLength = field.length;
    
    for (var i in field) {
      // Attach the truthy values upon the end of the array. 
      field.push(field[i]);
    }
    
    // Delete the original range within the array so that
    // only the new elements are preserved.
    field.splice(0, originalLength);
    

提交回复
热议问题