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

WBOY
WBOYOriginal
2016-05-16 16:16:321102browse

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

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