基础js

js的类型判断

2018-03-16  本文已影响0人  该昵称注册中

js的数据类型

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

Object类型:有Array Date jQuery Function

判断基础类型 typeof
typeof("aaa") => string
typeof(1234) => number 
typeof(null) => object
typeof 判断的null,array,object都是Object
判断Object类型 instanceof
[1,2,3] instanceof Array =>true
function fn(){}
fn instanceof Function => true
$("id") instanceof jQuery => true
都可以判断 Object.prototype.toString.call()

因为toString为Object的原型方法,而Array,function等类型作为Object的实例,都重写了toString方法,不同的对象类型调用toString方法时,根据原型链的知识,调用的是对应的重写之后的toString方法(function类型返回内容为函数体的字符串,Array类型返回元素组成的字符串.....),而不会去调用Object上原型toString方法(返回对象的具体类型),所以采用obj.toString()不能得到其对象类型,只能将obj转换为字符串类型;因此,在想要得到对象的具体类型时,应该调用Object上原型toString方法。

var arr = [1,2,3]
console.log(Object.prototype.toString.call(arr)) ==> "[object Array]")
var num= 8
console.log(Object.prototype.toString.call(num)) ==> "[object Number]")

console.log(Object.prototype.toString.call(null)) ==> [object Null]
jquery方法 $.type() 实现了Object.prototype.toString.call()
$.type(3) === "number" // true
$.type("test") === "string" //true
$.type(/test/) === "regexp" //true
有瑕疵的constructor
var crr = [1,23,45];
console.log(crr.constructor == Array) ==>true
//瑕疵
 function A(){};
 function B(){};
  A.prototype = new B(); //A继承自B
  var aObj = new A();
  alert(aobj.constructor === B) -----------> true;
  alert(aobj.constructor === A) -----------> false;
上一篇下一篇

猜你喜欢

热点阅读