Home > Web Front-end > JS Tutorial > body text

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

醉折花枝作酒筹
Release: 2021-06-15 09:14:19
Original
10526 people have browsed it

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()方法
});
Copy after login

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;  
}
Copy after login

[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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template