Unf*_*fra 14 javascript typescript
如何检查对象是否为空?
例如:
private brand:Brand = new Brand();
Run Code Online (Sandbox Code Playgroud)
我试过了:
if(this.brand)
{
console.log('is empty');
}
Run Code Online (Sandbox Code Playgroud)
不工作
Dee*_*Sea 24
使用Object.keys(obj).length检查,如果它是空的.
输出:3
资料来源:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
luk*_*s_o 16
这是两个最流行的答案之间的比较,它们的含义确实略有不同:
let o1 = {}
console.log(JSON.stringify(o1) === '{}')
console.log(Object.keys(o1).length === 0)
// true
// true
let o2 = { p: undefined }
console.log(JSON.stringify(o2) === '{}')
console.log(Object.keys(o2).length === 0)
// true
// false
let o3 = { l: null }
console.log(JSON.stringify(o3) === '{}')
console.log(Object.keys(o3).length === 0)
// false
// falseRun Code Online (Sandbox Code Playgroud)
adi*_*iga 10
您可以这样使用Object.keys:
class Brand { }
const brand = new Brand();
if (Object.keys(brand).length === 0) {
console.log("No properties")
}Run Code Online (Sandbox Code Playgroud)
如果要检查对象是否至少具有一个non-null,un-undefined属性:
Object.values()someconst hasValues =
(obj) => Object.values(obj).some(v => v !== null && typeof v !== "undefined")
class Brand { }
const brand = new Brand();
if (hasValues(brand)) {
console.log("This won't be logged")
}
brand.name = null;
if (hasValues(brand)) {
console.log("Still no")
}
brand.name = "Nike";
if (hasValues(brand)) {
console.log("This object has some non-null, non-undefined properties")
}Run Code Online (Sandbox Code Playgroud)
您还可以使用lodash来检查对象
if(_.isEmpty(this.brand)){
console.log("brand is empty")
}
Run Code Online (Sandbox Code Playgroud)
这是我所知道的最快的构造,尽管它使用了一些令人费解的for...in不循环的循环(在我的测试中,它大约比 2 倍快Object.keys)
export function isObjectEmpty(object: Record<string, unknown>): boolean {
for (const property in object) {
// if any enumerable property is found object is not empty
return false;
}
return true;
}
Run Code Online (Sandbox Code Playgroud)
let contacts = {};
if(Object.keys(contacts).length==0){
console.log("contacts is an Empty Object");
}else{
console.log("contacts is Not an Empty Object");
}
Run Code Online (Sandbox Code Playgroud)
Object.keys(myObject).length == 0
Run Code Online (Sandbox Code Playgroud)
可以使用空属性创建 Map obj,大小可能不起作用。对象可能不等于空或未定义
但是通过上面的代码你可以发现一个对象是否真的为空