Home  >  Article  >  Web Front-end  >  How to remove null values ​​from an array in javascript

How to remove null values ​​from an array in javascript

醉折花枝作酒筹
醉折花枝作酒筹Original
2021-06-11 17:26:3510515browse

Methods to remove null values ​​from arrays: 1. Use the filter method, syntax "array.filter(function (element value, index value, array object), value of this); 2. Use the splice method, syntax " Array object.splice(integer, number of items, new items added to the array)".

How to remove null values ​​from an array in javascript

The operating environment of this tutorial: Windows 7 system, JavaScript version 1.8.5, Dell G3 computer.

filter filtering method

var arr = ['A', '', 'B', null, undefined, 'C', '  '];
var r = arr.filter(function (s) {
    return s && s.trim(); // 注:IE9(不包含IE9)以下的版本没有trim()方法
});

splice method

function trimSpace(array){  
     for(var i = 0 ;i<array.length;i++)  
     {  
         if(array[i] == " " || array[i] == null || typeof(array[i]) == "undefined")  
         {  
                  array.splice(i,1);  
                  i= i-1;  

         }  
     }  
     return array;  
}

[Recommended learning: javascript advanced tutorial]

The above is the detailed content of How to remove null values ​​from an array in javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn