分享web开发知识

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

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

JS区分对象类型

发布时间:2023-09-06 01:56责任编辑:蔡小小关键词:暂无标签

Object.prototype.toString.call() 区分对象类型

在JavaScript中数据类型分为:1.基本类型,2.引用类型

  1. 基本类型:Undefined,Boolean,String,Number,Null
  2. 引用类型:Object (Array,Date,RegExp,Function)

var a = ‘hello world‘;var b = [];var c = function(){};
  • 1
  • 2
  • 3

我们用不同的判断类型的方法来判断上面三个变量的类型;(编译工具webStorm,浏览器Chrome) 
1.首先:typeof( )

1.console.log(typeof (a)+‘;‘+typeof (b)+‘;‘+typeof (c))输出:string;object;function
  • 1
  • 2

2.其次:instanceof

console.log(a instanceof Object) ???//falseconsole.log(b instanceof Object) ???//trueconsole.log(c instanceof Object) ???//trueconsole.log(a instanceof Array) ????//falseconsole.log(b instanceof Array) ????//trueconsole.log(c instanceof Array) ????//falseconsole.log(a instanceof Function) ?//falseconsole.log(b instanceof Function) ?//falseconsole.log(c instanceof Function) ?//true
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

从上面两个例题可以看出,typeof(),insctanceof,这两种方法都只能对简单的变量进行判断,如果比较复杂的变量判断时就会有误,不精确; 
下面我们介绍Object.prototype.toString.call()方法; 
3.Object.prototype.toString.call()

console.log(Object.prototype.toString.call(a))console.log(Object.prototype.toString.call(b))console.log(Object.prototype.toString.call(c))输出:[object String][object Array][object Function]
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

可以写个方法传值进入判断:

function isType(obj,type){ ???????if(obj != ‘‘){ ???????????return Object.prototype.toString.call(obj)===‘[object ‘+type+‘]‘ ???????}else{ ???????????alert(‘对象不能为空‘) ???????}} console.log(isType(‘hello world‘,‘String‘)) ?//true ??

JS区分对象类型

原文地址:https://www.cnblogs.com/0828-li/p/9102768.html

知识推荐

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