2017-09-03 170 views
-2

我有一個叫做isEmpty的功能。這裏是什麼樣子:該函數是否應該(「isEmpty」)檢查對象是否沒有參數?

/** 
* Returns true when the argument is empty. 
* 
* We define empty as: 
* - undefined 
* - null 
* - a string with length 0 
* - an array with length 0 
* - an object with no parameters: consider this? 
**/ 
function isEmpty(arg) { 

    return (arg === null) || 
     (arg === undefined) || 
     ((typeof (arg) === 'string') ? arg.length === 0 : false) || 
     ((Array.isArray(arg)) ? arg.length === 0 : false); 
} 

我想知道,這將是有益的也當一個對象沒有參數({})返回true?

+2

當一個對象有*無鍵或值你的意思是*? – Li357

+2

難道這不取決於你的用例是什麼? –

+0

是的。像'let a = {}; console.log(isEmpty(a))'logs' true' –

回答

1

答案是NO。它例如都返回false。 {}{age:67}

如果你想檢查對象是否有參數使用Object.getOwnPropertyNames()方法。它比for in循環或keys()方法更安全,因爲它檢查對象是否只有自己定義的屬性(無論其原型屬性如何)

var a = {}; 
var b = {name:'Paul'}; 

console.log(isObjectEmpty(a)); //true 
console.log(isObjectEmpty(b)); //false 

function isObjectEmpty(obj){ 
    return !Object.getOwnPropertyNames(obj).length; 
} 

如果你想保持你的功能,你可以使用

function isEmpty(arg) { 
    if(arg === null || typeof arg==='undefined') return true; 
    if(typeof arg==='string') return !arg.length; 
    if(arg.constructor.name==='Array') return !arg.length; 
    if(arg.constructor.name==='Object') return !Object.getOwnPropertyNames(arg).length; 
} 
2

根據您的用例,如果對象內部沒有鍵值對,則可以說對象爲空。由於數組也是一個對象,因此您可以檢查typeof arg === 'object',然後檢查您獲得的鍵數組的長度是否爲Object.keys()。同樣對於空字符串,您可以將arg與「」進行比較。事情是這樣的:

function isEmpty(arg) { 
 

 
return (arg === null) || 
 
    (arg === undefined) || 
 
    (arg === "") || 
 
    ((typeof arg === 'object') ? Object.keys(arg).length === 0 : false); 
 
} 
 

 
console.log(isEmpty(null)); 
 
console.log(isEmpty(undefined)); 
 
console.log(isEmpty([])); 
 
console.log(isEmpty({})); 
 
console.log(isEmpty(1));

+0

問題不在於**如何檢查一個空對象,或者如何優化他的代碼。問題是**應該檢查空對象是否爲「空」的一般概念的一部分,它沒有答案,因爲它純粹是如何定義和使用函數的問題。 – 2017-09-03 03:12:51

1

大概可以概括爲如果對象enumerable properties(或for...of的迭代對象)

function isEmpty(arg) { 
 
    for (e in arg) return false; 
 
    return true; 
 
} 
 

 
console.log(isEmpty(null), isEmpty(undefined)) 
 
console.log(isEmpty(""), isEmpty([]), isEmpty({})) 
 
console.log(isEmpty(0))    // doesn't work for Number, Boolean, Set, Map, etc. 
 
console.log(isEmpty("0"), isEmpty([0]), isEmpty({0:0}))

相關問題