JS检测数据类型的4种方法:
JS的数据类型(一共八种)
- Numer
- String
- Boolean
- undefined
- null
- object
- symbol
- bigint
typeof
- console.log(typeof "") String;
- console.log(typeof 1) Number;
- console.log(typeof true) Boolean;
- console.log(typeof null) Object;
- console.log(typeof undefined) undefined;
- console.log(typeof []) Object;
- console.log(typeof function(){}) Function;
- console.log(typeof {}) Object;
instanceof
1 console.log("1" instanceof String) false;
console.log(new String('1') instanceof String) true;
2 console.log(1 instanceof String) false;
console.log(new Number(1) instanceof Number) true;
3 console.log(true instanceof Boolean) false;
console.log(new Boolean(true) instanceof Boolean) true;
6 console.log([] instanceof Array) true ;
7 console.log(function(){} instanceof Function) true;
8 console.log({} instanceof Object) true;
constructor
1 console.log(("1").constructor === String);true
2 console.log((1).constructor === Number);true
3 console.log((true).constructor === Boolean);true
6 console.log(([]).constructor === Array);true
7 console.log((function() {}).constructor === Function);true
8 console.log(({}).constructor === Object);true
Object.prototype.toString.call()
1 var a = Object.prototype.toString;
3 console.log(a.call("aaa")); [object String]
4 console.log(a.call(1));[object Nmber]
5 console.log(a.call(true));[object Boolean]
6 console.log(a.call(null));[object Null]
7 console.log(a.call(undefined));[object Undefined]
8 console.log(a.call([]));[object Array]
9 console.log(a.call(function() {}));[object Function]
10 console.log(a.call({}));[object Object]