问题描述
我只是想知道为什么当我多次调用“hasOwnProperty”方法时,控制台中只返回一个布尔值?返回的始终是最终调用。 我的其余代码功能齐全,如果我切换顺序,我会检查 3 个属性在哪里,它会返回最后一个调用。
spot.hasOwnProperty("sit");
spot.hasOwnProperty("name");
spot.hasOwnProperty("species");
伙计们干杯。
解决方法
它们都返回了,但控制台只显示最新命令的输出;您可以将它们放在一个数组中以一次查看所有响应
[spot.hasOwnProperty('sit'),spot.hasOwnProperty('name')]
,
缺乏上下文,我假设这归结为布尔逻辑。如果您一次检查一个操作,您将获得正确的值。
var spot = {};
spot.sit = true;
//spot.name = "Spot";
spot.species = "dog";
console.log(spot.hasOwnProperty('sit'));
console.log(spot.hasOwnProperty('name'));
console.log(spot.hasOwnProperty('species'));
如果您一次检查所有值,有 2 个选项:布尔与 (&&
) 或布尔或 (||
)。
var spot = {};
//spot.sit = true;
spot.name = "Spot";
spot.species = "dog";
// Boolean OR
console.log(spot.hasOwnProperty('sit') || spot.hasOwnProperty('name') || spot.hasOwnProperty('species'));
// Boolean AND
console.log(spot.hasOwnProperty('sit') && spot.hasOwnProperty('name') && spot.hasOwnProperty('species'));