Javascript 数据类型

一、js的数据类型

   1、基本类型:字符串类型(string),数字类型(number),布尔类型(boolean)

   2、复杂类型:数组类型(array),对象类型(object),函数类型(function),正则类型(regexp)

   3、空类型:undefine  和 null

二、javascript中类型检测方法有很多,简要介绍一下两种:

  • typeof
  • instanceof

1、typeof

   typeof  100                "number"
   typeof   nan               "number "
   typeof  false              " boolean"
   typeof   function         "function "
   typeof   (undefined)   "undefined "
   typeof   null                "object "
   typeof   [1,2]               "object " 
            

 特殊的是typeof null返回“object”

typeof对基本类型和函数对象很方便,但是其他类型就没办法了。

例如想判断一个对象是不是数组?用typeof返回的是“object”。所以判断对象的类型常用instanceof。

2、instanceof  运算符用来检测 constructor.prototype 是否存在于参数 object 的原型链上。instanceof只能用来判断对象和函数,不能用来判断字符串和数字等

obj instanceof Object 检测Object.prototype是否存在于参数obj的原型链上。

function Person(){};
var p =new Person();
console.log(p instanceof Person);   //true

继承中判断实例是否属于它的父类

Student和Person都在s的原型链中:

function Person(){};
function Student(){};
var p =new Person();
Student.prototype=p;//继承原型
var s=new Student();
console.log(s instanceof Student);//true
console.log(s instanceof Person);//true
var oStringObject = new String("hello world"); 
console.log(oStringObject instanceof String);   // 输出 "true"

 

 

 

posted @ 2017-09-25 22:06  Apple-fly  阅读(129)  评论(0编辑  收藏  举报