Home > Article > Web Front-end > How to remove null values from an array in javascript
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)".
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!