JavaScript - Check Object type & property exist or not

1.Check Object type

1:  var anObj = { job: "I'm an object!" };  
2:  var aNumber = 42;  
3:  var aString = "I'm a string!";  
4:  console.log(typeof anObj); // should print "object"  
5:  console.log(typeof aNumber); // should print "number"  
6:  console.log(typeof aString); // should print "string"  


2.Check property existence

1:  var myObj = {  
2:    name: "Piao Guangyuan"  
3:  };  
4:  console.log( myObj.hasOwnProperty('name') ); // should print true  
5:  console.log( myObj.hasOwnProperty('nickname') ); // should print false  

No comments:

Post a Comment