js 非空判斷


  1. 是否為 null
  2. 是否為 ""
  3. 是否為空字符串(引號中間有空格)  如: "     "。
  4. 制表符、換行符、換頁符和回車

一. 字符串

1. if(str == null || str == "")                 非空 if(str != null && str != "")

2. if(str == null || str.isEmpty())                  if(str != null && !str.isEmpty())

3.if (str == null  || "".equals(str.trim()))       if (str != null && !"".equals(str.trim()))

4.if(str == null   || str.length()<=0)              if(str != null && str.length()>0)

5.if(str == null || "".equals(str))                  if(str != null && !"".equals(str))

6.if(StringUtils.isBlank(str))                       if(StringUtils.isNotBlank(str))                  import org.apache.commons.lang3.StringUtils;判斷的是str.length(),相當於4

二.數組

1.arr==null || (arr!=null &&arr.length==0)           非空  arr!=null || (arr==null &&arr.length!=0) 

三.List集合

1.if(list == null || list.isEmpty())            非空  if(list != null && !list.isEmpty())

2.if(list == null || list.size() == 0)                    if(list != null && list.size() > 0)

3.if(list == null || StringUtils.isEmpty(list))     if(list != null && !StringUtils.isEmpty(list))

4.if (CollectionUtils.isEmpty(list))                  if (CollectionUtils.isNotEmpty(list))      等同於2

四.Map

1.if (MapUtils.isEmpty(map))                    非空  if (MapUtils.isNotEmpty(map))      等同於2

2.if(map== null || map.size() == 0)                     if(map!= null && map.size() > 0)

3.if(map== null || StringUtils.isEmpty(map))      if(map!= null && !StringUtils.isEmpty(map))

null和isEmpty()的區別

  1. 這就相當於去商店買東西
  2.  null 首先判斷是否有商店(new ArrayList();)
  3.  isEmpty()沒有判斷商店是否存在,而是判斷商店是否有東西,如果連商店都沒有,何來的的東西可賣(list.add(商品))


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM