JavaScript检测数据类型

1.typeoftypeof 操作符是确定一个变量是String、Number、Boolean、undefined的最佳工具引用来源:《JavaScript高级程序设计》图灵程序设计丛书看下面例子:var s = ‘hello’;var num = 10;var bool = true;var und;typeof s; // “string"typeof num; // “number"typeof bool; // “boolean"typeof und; // “undefined"ok,都检测出来了,but, 如果检测的是一个对象或者null,皆会返回Objectvar n = null;var o = new Object();typeof n; // “object"typeof o; // “object"看吧,一点区分度也没有。所以: 在检测基本数据类型时,typeof很好用,在检测引用类型的值时,typeof的作用不大2.instanceofvar o = new Object();var arr = [];var reg = /^abc$/o instanceof Object //truearr instanceof Array //truereg instanceof RegExp //true注意:使用instanceof操作符检测基本数据类型的值时,都会返回false,尽管下面的例子看起来很矛盾null instanceof Object // falsetypeof null // “object"3.Object.prototype.toString()ECMA-262 规范中,toString方法是这样定义的:如果参数是未定义的值,则返回”[object Undefined]".如果参数为null,则返回”[object Null]".如果适用ToObject函数传递参数,则返回对象.如果参数为类,则返回包含对象的类.(Let class be the value of the [[Class]] internal property of O.)返回一个由”[对象”, 类, 和”]“拼接而成的字符串.它可以返回引用类型更精准的类型检测var o = new Object();var arr = [];var reg = /^abc$/Object.prototype.toString.call(o) // “[object Object]“Object.prototype.toString.call(arr) // “[object Array]“Object.prototype.toString.call(reg) // “[object RegExp]“通过函数封装处理一下:var type = function (o) { var s = Object.prototype.toString.call(o); return s.match(/[object (.*?)]/)[1];}type(o) // “Object"type(reg) // “RegExp"type(arr) // “Array” ...

April 20, 2019 · 1 min · jiezi

javascript 判断数据类型的几种方法

javascript 判断数据类型的几种方法一、typeof 直接返回数据类型字段,但是无法判断数组、null、对象typeof 1"number"typeof NaN"number"typeof “1"“string"typeof true"boolean"typeof undefined"undefined"typeof null"object"typeof []“object"typeof {}“object"其中 null, [], {}都返回 “object"二、instanceof 判断某个实例是不是属于原型// 构造函数function Fruit(name, color) { this.name = name; this.color = color;}var apple = new Fruit(“apple”, “red”);// (apple != null)apple instanceof Object // trueapple instanceof Array // false三、使用 Object.prototype.toString.call()判断call()方法可以改变this的指向,那么把Object.prototype.toString()方法指向不同的数据类型上面,返回不同的结果Object.prototype.toString.call(1)"[object Number]“Object.prototype.toString.call(NaN);"[object Number]“Object.prototype.toString.call(“1”);"[object String]“Object.prototype.toString.call(true)"[object Boolean]“Object.prototype.toString.call(null)"[object Null]“Object.prototype.toString.call(undefined)"[object Undefined]“Object.prototype.toString.call(function a() {});"[object Function]“Object.prototype.toString.call([]);"[object Array]“Object.prototype.toString.call({});"[object Object]“最后我们可以修改一下原型上的typeof方法或者在自己的对象上面重新定义一个方法typeof()function _typeof(obj){ var s = Object.prototype.toString.call(obj); return s.match(/[object (.*?)]/)[1].toLowerCase();};

February 15, 2019 · 1 min · jiezi