js 判断对象存在某个值
时间: 2023-07-25 22:25:58 浏览: 74
可以使用 `Object.values()` 方法获取对象的所有属性值,然后使用 `Array.includes()` 方法判断指定的值是否在这些属性值中。示例如下:
```javascript
const obj = { name: 'John', age: 25, gender: 'male' };
if (Object.values(obj).includes('male')) {
console.log('obj has male value');
}
if (Object.values(obj).includes('female')) {
console.log('obj has female value');
} else {
console.log('obj does not have female value');
}
```
输出结果为:
```
obj has male value
obj does not have female value
```
另外,如果要检查某个属性值是否等于指定的值,可以直接使用 `===` 运算符进行比较。示例如下:
```javascript
const obj = { name: 'John', age: 25, gender: 'male' };
if (obj.gender === 'male') {
console.log('obj has male gender');
}
if (obj.gender === 'female') {
console.log('obj has female gender');
} else {
console.log('obj does not have female gender');
}
```
输出结果与上面的示例相同。
阅读全文