一次性搞定参数判空

let str1 = ''
let arr1 = []
let obj1 = {}
let sth1 = null
let data = undefined
console.log('str1:',str1) 
console.log('arr:',arr1)
console.log('obj1:',obj1)
console.log('sth1:',sth1)
console.log('data:',data)

console.log('str1:',!str1)
console.log('arr:',!arr1)
console.log('obj1:',!obj1)
console.log('sth1:',!sth1)
console.log('data:',!data)

结果展示
str1: 
arr: []
obj1: {}
sth1: null
data: undefined
!str1: true
!arr: false
!obj1: false
!sth1: true
!data: true

let str2 = 'str'    
console.log('str2:',str2)
console.log('!str2:',!str2)

结果展示
str2: str
!str2: false

结论: 空字符串 ''  undefined  null 取反均为 true

      空对象{  }   空数组[ ] 取反均为 false 

      非空字符串取反 为false   

 


 str1 ? console.log('1') : console.log('2')  //2
 str2 ? console.log('1') : console.log('2')  //1
 arr1 ? console.log('1') : console.log('2')  //1
 obj1 ? console.log('1') : console.log('2')  //1
 sth1 ? console.log('1') : console.log('2')  //2
 data ? console.log('1') : console.log('2')  //2

所以我们可以这样判断

posted @ 2022-04-08 07:24  zhangzhebokeyuan  阅读(66)  评论(0编辑  收藏  举报