Home > Web Front-end > JS Tutorial > JavaScript custom function sharing to determine whether a variable is empty_javascript skills

JavaScript custom function sharing to determine whether a variable is empty_javascript skills

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-05-16 16:16:32
Original
1161 people have browsed it

JavaScript itself does not have a function to determine whether a variable is null, because variables may be string, object, number, boolean, etc. Different types require different determination methods. So I wrote a function in the article to determine whether the JS variable is empty. If it is undefined, null, '', NaN, false, 0, [], {}, and blank string, it will return true, otherwise it will return false.

Copy code The code is as follows:

function isEmpty(v) {
switch (typeof v) {
case 'undefined':
        return true;
case 'string':
If (v.replace(/(^[ tnr]*)|([ tnr]*$)/g, '').length == 0) return true;
         break;
case 'boolean':
If (!v) return true;
         break;
case 'number':
If (0 === v || isNaN(v)) return true;
         break;
case 'object':
If (null === v || v.length === 0) return true;
for (var i in v) {
              return false;
}
        return true;
}
Return false;
}

Test:

Copy code The code is as follows:

isEmpty()                                    //true
isEmpty([]) //true
isEmpty({}) //true
isEmpty(0) //true
isEmpty(Number("abc")) //true
isEmpty("") //true
isEmpty(" ") //true
isEmpty(false) //true
isEmpty(null) //true
isEmpty(undefined) //true

Related labels:
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
Latest Issues
What are JavaScript hook functions?
From 1970-01-01 08:00:00
0
0
0
What is JavaScript garbage collection?
From 1970-01-01 08:00:00
0
0
0
c++ calls javascript
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template