我有一个JS对象(键值对),这些值可以是未定义的。但是,如果只定义了值的一个,我希望代码可以执行其他操作。最简单、最有效的检查方法是什么?(请参阅下面的片段以澄清)
let obj = {x:undefined, y:undefined, z:1337}
let otherobj = {x:undefined, y:undefined, z:undefined}
let anotherobj = {x:1,y:2,z:3}
if(foo(obj) && !foo(otherobj) && !foo(anotherobj)){
alert("!!!");
}
function foo(x){
return true; // ???
}
发布于 2022-08-31 12:39:46
,但如果只定义了其中一个值,则代码将执行其他操作。
您可以使用filter只获取非“未定义”的值。
THen使用.length === 1检查它是否正好是1值
let obj = {x:undefined, y:undefined, z:1337}
let otherobj = {x:undefined, y:undefined, z:undefined}
let anotherobj = {x:1,y:2,z:3}
console.log('Test 1', objHasOneValue(obj)); // true
console.log('Test 2', objHasOneValue(otherobj)); // false
console.log('Test 3', objHasOneValue(anotherobj)); // false
function objHasOneValue(x){
return Object.values(x).filter(a => a !== undefined).length === 1;
}
https://stackoverflow.com/questions/73555949
复制相似问题