JS How to Determine If an Object Contains an Attribute
- 2021-08-09 06:44:38
- OfStack
1. Using in keyword will return true/false pro-test can be realized!
// Create an object data
var data = scope.data;
// Judge update The value is' Yes ' When, data There must be in it 'userXM' And 'mobile' Two fields, and neither is empty
if(scope.update == " Yes "){
if(!('userXM' in data)||!( 'mobile' in data)){
// Code that does not contain fields, executes
}else if(data["userXM"] == ""|| data["mobile"] == ""){
// Two values, or where 1 Code executed when the value is null
}else{
}
}
var obj = {name:'jack'};
alert('name' in obj); // --> true
alert('toString' in obj); // --> true
2. hasOwnProperty method
This method returns a Boolean value indicating whether the object has the specified property in its own properties (that is, whether it has the specified key).
var obj = {name:'jack'};
obj.hasOwnProperty('name'); // --> true
obj.hasOwnProperty('toString'); // --> false
3. Use undefined to judge
var o={x:1};
o.x!==undefined; //true
o.y!==undefined; //false
o.toString!==undefined //true