数据类型判断方法超详细讲解

222 阅读2分钟

1.typeof

1.判断数据类型返回结果:

基本数据类型:string,number,boolean,undefined

引用数据类型:object (不管是什么引用类型就返回object),function

2.typeof判断变量是否存在

typeof a!="undefined"

 let s;
 function fun() {
  let text=1; 
 }
 typeof "123"  //string
 typeof 123   //number
 typeof true  //boolean
 typeof a    //undefined
 typeof s    //undefined
 typeof fun   //function
 typeof [1]  //object
 typeof {}   //object

 

2.instanceof

1.A instanceof B 

可以判断A是不是B的实例,返回一个布尔值,由构造类型判断出数据类型

instanceof 检测的是原型

2.数组,函数都属于Object 会返回true

 function fun() {
  le a=1; 
 }
 [] instanceof Object //true 数组属于object
 fun instanceof Object //true function 属于object


 {} instanceof Object //true
 [] instanceof Array //true
 fun instanceof Function //true

3.手动实现instanceof方法

function myInstanceOf(A, B) {
    let a = A.__proto__;
    let b = B.prototype;
    return a == b// A的内部属性 __proto__ 指向 B 的原型对象
  }
  myInstanceOf([], Object) //false
  
  function Person() { };
  myInstanceOf(new Person(), Person)//true

3.constructor

1.讲解

constructor是原型prototype的一个属性。

当函数被定义时候,js引擎会为函数添加原型prototype,然后再在 prototype上添加一个 constructor 属性,并让其指向函数的引用。

例子:当执行 var f = new F() 时,F 被当成了构造函数,f 是F的实例对象,此时 F 原型上的 constructor 传递到了 f 上,因此 f.constructor == F

function F() {}
var f = new F();
f.constructor == F;//true

2.数据类型判断

 function fn() { };
 [].constructor == Array;     //true
 [].constructor == Object;    //false
 fn.constructor === Function; //true
 "123".constructor === String;//true

3.null ,undefined 是无效对象,因此不会有 constructor 存在,需要其他方式判断

 undefined.constructor === Number //直接报错

4.toString()

Object.prototype.toString.call()

1.tostring()是Object的方法,可把数据转化为字符串;也可以检测复合型数据的类型

例如:对象、数组、函数、正则表达式、错误对象、宿主对象、自定义类型对象等;

不同类型对象调用 toString() 方法时返回的字符串格式并不统一;

因为不同类型的子类在继承 Object 的原型方法 toString,时重写了该方法。

如果在对象上调用 Object 的原型方法 toString(),就会返回统一格式的字符串表示

因此写法是:Object.prototype.toString 

直接调用:

 var o = {}; //对象
 var a = [1, 2]; //数组
 var f = function () { }; //函数
o.toString();//[object Object]
a.toString();//1,2
f.toString();//function () { }

调用原型上面的:

var _toString = Object.prototype.toString;  //引用 Objget 的原型方法 toString ()
_toString.call({});//使用call,apply方法在对象上动态调用Object的原型方法 toString ()
_toString.call("1,2,3");//[object String]
_toString.call([1, 2, 3]);//[object Array]
_toString.call(f);//[object Function]
_toString.call(true); //[object Boolean]

5.准确判断数组类型方法

5.1 Array.isArray()

Array.isArray([1,2,4]);//true

5.2 constructor

[].constructor== Array; //true

5.2 Object.prototype.toString.call()

Object.prototype.toString.call[]); //[objdect array]