【发布时间】:2019-04-10 18:20:13
【问题描述】:
我有
my_map: { [name: string]: string }
如何检查 hashmap my_map 是否为空?
我可以想到Object.keys(my_map).length === 0,但感觉有点矫枉过正。
【问题讨论】:
标签: typescript dictionary hash hashmap
我有
my_map: { [name: string]: string }
如何检查 hashmap my_map 是否为空?
我可以想到Object.keys(my_map).length === 0,但感觉有点矫枉过正。
【问题讨论】:
标签: typescript dictionary hash hashmap
有趣的是,您的矫枉过正的解决方案实际上是矫枉过正;你需要更进一步:
Object.keys(obj).length === 0 && obj.constructor === Object
例子:
function isEmptyUnderkill(obj: any) {
return Object.keys(obj).length === 0;
}
function isEmptyObject(obj: any) {
return Object.keys(obj).length === 0 && obj.constructor === Object;
}
const a = {};
const b = { name: 'User' };
console.log(isEmptyUnderkill(a), isEmptyObject(a));
console.log(isEmptyUnderkill(b), isEmptyObject(b));
console.log(isEmptyUnderkill(new Date()), isEmptyObject(new Date()));
给予:
true true
false false
true false
【讨论】: