我想要判断一个Java脚本对象,看看它的任何属性是否丢失,而不是单独判断每个属性.
我可以使用"hasownProperty"或do if/Else语句来判断它们是否都是空的/未定义的,我想要一种判断对象的更短的方法.
我想要判断一个Java脚本对象,看看它的任何属性是否丢失,而不是单独判断每个属性.
我可以使用"hasownProperty"或do if/Else语句来判断它们是否都是空的/未定义的,我想要一种判断对象的更短的方法.
对对象值使用Array::some()
(用Object.values()
获取它们)(如果ANY属性值为null
或undefined
,则返回true
):
const obj = { a: null, b: 'there', c: 0, d: undefined };
console.log("Missing?", Object.values(obj).some(v => v === undefined || v === null));
如果您希望它尽可能快,请编写您自己的函数:
const obj = { a: null, b: 'there', c: 0, d: undefined };
function hasNullProperties(obj){
for(const k in obj){
if(obj[k] === undefined || obj[k] === null){
return true;
}
}
return false;
}
console.log("Missing?", hasNullProperties(obj));
和一个基准:
<script benchmark data-count="10000000">
const obj = { a: null, b: 'there', c: 0, d: undefined };
// @benchmark Array::some()
Object.values(obj).some(v => v === undefined || v === null);
// @benchmark custom func
function hasNullProperties(obj){
for(const k in obj){
if(obj[k] === undefined || obj[k] === null){
return true;
}
}
return false;
}
// @run
hasNullProperties(obj);
</script>
<script src="https://cdn.jsdelivr.net/gh/silentmantra/benchmark/loader.js"></script>