JavaScript基础之判断数据类型的三种方式

前面聊的时候说了一个方法判断是否为某个类型的关键字:instanceof,前后还聊了一个typeof判断数据类型,但其又有什么区别呢?以及判断类型的补充tostring.

typeof

这个是JavaScript中第一个使用判断数据类型的关键字,尤其是在基本数据类型的时候。

typeof "abc"; //"string"
typeof  1; //"number"
typeof null;//"object"
typeof undefinded;// "undefinded"

在这里插入图片描述

判断数据类型发,然后返回一个字符串。

当然也可以用来判断方法:

function test(){
    
    }; 
typeof test//"function"

test1=function(){
    
    };
typeof test1;//"function"

在这里插入图片描述

好像也也可以,但是如果判断一个对象和数组的时候呢?

arr =[1,3];
typeof arr; //"object"

obj={};
typeof obj;//"object"

在这里插入图片描述

  • 基本类型和函数会判断出类型。
  • 除函数外所有的引用类型都会判断为object。

所以typeof只能适用于基本类型和函数会判断出类型,以及函数。返回一个数据类型的字符串

instanceof

这个还是老规矩,先来代码,前面说过这个是判断对象的,所以来一波对象。

a=new Number(1);
a instanceof Number; //true

arr=[1,3];
arr instanceof Array; //true


new Date() instanceof Date//true 


在这里插入图片描述

然后再判断方法

function test(){}; 
test instanceof Function ;  //true

test1=function(){};
test1 instanceof Function ;//true

在这里插入图片描述

那基本数据类型呢?

12 instanceof Number;
// 这个会很神奇 结果是false

在这里插入图片描述

为什么会出现这样的情况?看下面代码理解。

arr=[1,3];
arr instanceof Array; //true

在这里插入图片描述

看到上面可以简单猜想instanceof判断数据类型于原型或者原型链有关。现在开始认证

function Per(){
    
    };
function PerObject(){
    
    };
Per.prototype=PerObject;
var p= new  Per();

在这里插入图片描述

p instanceof Per;// true 

p instanceof PerObject //false
  • 使用instanceof必须是引用类型。
  • 而且是什么类型,先看本身如果本身没有这个类型,就会找其原型链上的,不过找到最近的一个,就不会继续向上找了。比如 [] instanceof Array;

可以看出instanceof只使用于引用类型,对基本数据类型就无法判断了.

toString

一般是的tostring判断数据类型的时候只得是调用Object.prototype.toString这个方法。而这中方式才是工作中用来判断数据类型的方式,因为其判断的数据类型最全。

在前面聊原型和原型链的时候,说过了会万物都是继承了Object,但是其方法有些会根据自己重写。

arr=[1,34]
arr.tostring();

在这里插入图片描述

前面聊this的时候说过通过一些关键字可以修改this指向。

Object.prototype.toString.call(arr)

在这里插入图片描述

这个就直接看代码

Object.prototype.toString.call(1);
Object.prototype.toString.call("a");

function test(){};
Object.prototype.toString.call(test);
Object.prototype.toString.call(true);

在这里插入图片描述

おすすめ

転載: blog.csdn.net/u011863822/article/details/121477773