分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 运营维护

js判断对象类型

发布时间:2023-09-06 02:06责任编辑:胡小海关键词:js

1.typeof

typeof只能判断区分基本类型,number、string、boolean、undefined和object,function;

typeof 0; ?//number;typeof true; ?//boolean;typeof undefined; ?//undefined;typeof "hello world" ??//string;typeof function(){}; ??//function;typeof null; //objecttypeof {}; ?//object;typeof []; //object

从上例我们可以看出, typeof  判断对象和数组都返回object,因此它无法区分对象和数组。

2.instanceof

var a={};a instanceof Object ?//truea intanceof Array ????//falsevar b=[];b instanceof Array ?//trueb instanceof ?Object //true

因为数组属于object中的一种,所以数组instanceof object,也是true.

var c=‘abc‘;c instanceof String; //falsevar d=new String();d instanceof String ?//true

instanceof不能区分基本类型string和boolean,除非是字符串对象和布尔对象。如上例所示。

3.constructor  

var o={};o.constructor==Object ?//truevar arr=[];arr.constructor==Array ?//truearr.constructor==Object //false

可以看出constructor可以区分Array和Object。

var n=true;n.constructor==Boolean ?//truevar num=1;num.constructor==Number ?//truevar str=‘hello world‘;str.constructor==String ????//true

var num=new Number();

num.constructor==Number   //true

 

不过要注意,constructor属性是可以被修改的,会导致检测出的结果不正确

function Person(){ ?}function Student(){ ?}Student.prototype = new Person();var John = new Student();console.log(John.constructor==Student); // falseconsole.log(John.constructor==Person); // true
除了undefined和null,其他类型的变量均能使用constructor判断出类型.

4.Object.prototype.toString.call()   ---------最好用

Object.prototype.toString.call(123)//"[object Number]"Object.prototype.toString.call(‘str‘)//"[object String]"Object.prototype.toString.call(true)//"[object Boolean]"Object.prototype.toString.call({})//"[object Object]"Object.prototype.toString.call([])//"[object Array]"

封装一个判断数组和对象的方法

function typeObj(obj){ ?????var type=Object.prototype.toString.call(obj); ?????if(type==‘[object Array]‘){ ???????return ‘Array‘; ?????}elseif(type==‘[object ?Object]‘){ ???????return ‘Object‘; ?????}else{ ???????return "obj is not object or array" ?????}}

Object.prototype.toString方法的在被调用的时候,会执行如下的操作步骤: 

1. 获取对象的类名(对象类型)。  

[[Class]]是一个内部属性,所有的对象(原生对象和宿主对象)都拥有该属性.在规范中,[[Class]]是这么定义的: 
内部属性,[[Class]] 一个字符串值,表明了该对象的类型。
2. 然后将[object  获取的对象类型的名]组合为字符串 
3. 返回字符串 “[object Array]” 。

5.jQuery中的  $.type接口

$.type(obj) ;

$.isArray(obj);

$.isFunction(obj);

$.isPlainObject(obj);

$.type([]) ???//array$.isArray([]); //true$.isFunction(function(){}); //true$.isPlainObject({}); //true$.isPlainObject([]); //false

js判断对象类型

原文地址:https://www.cnblogs.com/sunmarvell/p/9386075.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved