廢話很少說先來總結:函數
/**總結: * 1.typeof能準確判斷出基本數據類型,可是不能判斷引用數據類型。判斷引用類型時除function外其餘判斷結果都爲object。 * 2.instanceof 不能判斷基本數據類型,可是能準確判斷引用數據類型。這是由於instanceof是經過可否找到構造函數的原型對象來判斷的。 * 3.Object.prototype.toString.call()能準確判斷任何數據類型 */
js中數據類型分爲兩大類:基本數據類型和引用數據類型。JS基本數據類型(按值問):Number,String,Boolean,null,undefined,Symbol
prototype
引用數據類型(按引用訪問):Object,Array,function
code
具體示例以下:對象
let num=111; let str='hello'; let flag=true; /**引用數據類型 */ let arr=[1,2,3]; let obj={name:'zhangsan',age:18}; const func=function(){ console.log('---function'); }; /**typeof判斷數據類型 */ console.log(typeof num);//number console.log(typeof str);//string console.log(typeof flag);// boolean console.log(typeof null);//object---null自己就是對象,經常使用來函數中返回不存在的對象。 console.log(typeof undefined);//undefined console.log(typeof Symbol);//function console.log(typeof arr);//object console.log(typeof obj);//object console.log(typeof func);//function /**typeof 判斷數據類型總結:typeof能很好的判斷基本數據類型,可是對於引用數據類型不能很好判斷。 * 引用數據類型除function能判斷外,其餘判斷結果都爲object。 */ /**instanceof判斷引用數據類型 */ console.log(num instanceof Number);//false console.log(str instanceof String);//false console.log(flag instanceof Boolean);//false console.log(Symbol instanceof Symbol);//false console.log(arr instanceof Array);//true console.log(obj instanceof Object);//true console.log(func instanceof Function);//true /**instanceof判斷數據類型總結:instanceof不能判斷基本數據類型,能判斷引用數據類型 */ /**Object.prototype.toString.call()判斷數據類型 */ console.log(Object.prototype.toString.call(num));//[object Number] console.log(Object.prototype.toString.call(str));// [object String] console.log(Object.prototype.toString.call(flag));// [object Boolean] console.log(Object.prototype.toString.call(null));// [object Null] console.log(Object.prototype.toString.call(undefined));// [object Undefined] console.log(Object.prototype.toString.call(Symbol));// [object Function] console.log(Object.prototype.toString.call(arr));//[object Array] console.log(Object.prototype.toString.call(obj));// [object Object] console.log(Object.prototype.toString.call(func));// [object Function]