標籤:return cti ace http [] style bit false scn
JavaScript本身沒有判斷一個變數是不是空值的函數,因為變數有可能是string,object,number,boolean等類型,類型不同,判斷方法也不同。所以在文章中寫了一個函數,用以判斷JS變數是否空值,如果是undefined, null, ‘‘, NaN,false,0,[],{} ,空白字串,都返回true,否則返回false
方法:
function isEmpty(v) { switch (typeof v) { case ‘undefined‘: return true; case ‘string‘: if (v.replace(/(^[ \t\n\r]*)|([ \t\n\r]*$)/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;}
測試:
isEmpty() //trueisEmpty([]) //trueisEmpty({}) //trueisEmpty(0) //trueisEmpty(Number("abc")) //trueisEmpty("") //trueisEmpty(" ") //trueisEmpty(false) //trueisEmpty(null) //trueisEmpty(undefined) //true
轉載:http://www.bitscn.com/school/Javascript/201503/463294.html
javascript判斷變數是不是空值