Skip to content

Instantly share code, notes, and snippets.

@hehongwei44
Created July 9, 2014 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hehongwei44/1d808ca9b7c67745f689 to your computer and use it in GitHub Desktop.
Save hehongwei44/1d808ca9b7c67745f689 to your computer and use it in GitHub Desktop.
变量的类型检查方式
/**
*
* js的类型检测方式->typeof、constuctor。
* 推荐通过构造函数来检测变量的类型。
*/
var obj = {key:'value'},
arr = ["hello","javascript"],
fn = function(){},
str = "hello js",
num = 55,
bool = true,
User = function(){},
user = new User();
/*typeof测试*/
console.log(typeof obj); //obj
console.log(typeof arr); //obj
console.log(typeof fn); //function
console.log(typeof str); //string
console.log(typeof num); //number
console.log(typeof bool); //boolean
console.log(typeof user); //object
/*constructor测试*/
console.log(obj.constructor == Object); //true
console.log(arr.constructor == Array); //true
console.log(str.constructor == String); //true
console.log(num.constructor == Number); //true
console.log(bool.constructor == Boolean);//true
console.log(user.constructor == User); //true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment