經(jīng)典面試題: 如何判斷一個(gè)對(duì)象為空對(duì)象?文章來源:http://www.zghlxwxcb.cn/news/detail-762273.html
方法一: 將對(duì)象轉(zhuǎn)換成字符串,在判斷是否等于{}
let obj = {}
let bool = JSON.stringify(obj) === '{}'
console.log(bool) // 返回true
方法二:循環(huán)for…in…
let res = (obj)=> {
for(let key in obj) {
retrun false
}
return true
}
console.log(res(obj)) // true 空對(duì)象
方法三: ES6中Object.keys()方法,返回對(duì)象的屬性名組成一個(gè)數(shù)組,若長度為0,則空對(duì)象
console.log(Object.keys(obj).length === 0) // true 空對(duì)象
// 提交表單時(shí)判斷某個(gè)值是不是空
let flag = Object.keys(this.formData).every(key => this.formData[key])
if (!flag) {
this.$toast("請檢查完成表單")
return
}
方法四: Object.getOwnPropertyNames(obj)獲取對(duì)象的屬性名,存到數(shù)組中,若長度為0,則為空對(duì)象
console.log(Object.getOwnPropertyNames(obj).length === 0) // true
方法五: js方法 Reflect.ownKeys()
const isEmpty = obj => Reflect.ownKeys(obj).length === 0 && obj.constructor === Object
console.log(isEmpty({})) // true
console.log(isEmpty({age:11})) // false
空值如何判斷?文章來源地址http://www.zghlxwxcb.cn/news/detail-762273.html
let checkNull = val => val === undefined || val === null || val === ''
console.log(checkNull(123))
console.log(checkNull())
console.log(checkNull(''))
//舊寫法
if(value !== null && value !== 'undefined' && value !== '' && typeOf(value) != 'undefined'){
//...
}
//新寫法
if( (value??'') !== ""){
}
|| 和 ??的區(qū)別
數(shù)值為 "" 或者 0 時(shí),
|| 為 false ?? 為true。
到了這里,關(guān)于js--判斷一個(gè)對(duì)象為空對(duì)象幾種方法的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!