当前位置:网站首页>Determine whether an attribute exists in an object

Determine whether an attribute exists in an object

2022-06-28 05:20:00 Zhangshao

Determine whether an attribute exists in the object

Write it correctly

/** *  Determine whether an attribute exists in the object  * @param {Object} obj  object  * @param {Sting} key  Property name  */
function hasProperty(obj,key){
    
  return key in obj;
}

Wrong writing

function hasProperty(obj,key){
    
  return obj.key !== undefined; // The wrong way out. 
}

function hasProperty(obj,key){
    
  return obj[key] !== undefined;  // The value of an attribute in an object cannot be determined to be undefined Properties of 
}
 Such as 
var obj = {
    a:undefined}
function hasProperty(obj,key){
    
 	return Object.keys(obj).includes(key)
}

// Unable to get usage defineProperty Properties added 
Object.defineProperty(obj,'c',{
    
  enumberable:false,
  value: 1
})

function hasProperty(obj,key){
    
 	return obj.hasOwnProperty(key) // Unable to find data on prototype chain 
}
原网站

版权声明
本文为[Zhangshao]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/179/202206280413400411.html