5种基本数据类型:Undefined、Null、Boolean、Number和String。

1中复杂数据类型:Object

使用typeof检测

typeof操作符返回一个字符串,表示未经求值的操作数的类型。

typeof可能的返回值:

  • "undefined"——如果这个值未定义;
  • "boolean"——如果这个值是布尔值;
  • "string"——如果这个值是字符串;
  • "number"——如果这个值是数值;
  • "object"——如果这个值是对象或 null;
  • "function"——如果这个值是函数。

注意事项:

typeof null 返回 object。

typeof 是一个操作符而不是函数,圆括号尽管可以使用,但不是必需的。

//typeof str 或者 typeof(str) 均可以

使用instanceof检测

用来检测引用类型:知道一个值是什么类型的对象。返回true/false。

所有引用类型的值都是 Object 的实例。

  • 如果使用 instanceof 操作符检测基本类型的值,则该操作符始终会返回 false,因为基本类型不是对象。但是使用new关键字构造基本数据的包装对象的实例时instanceof操作符也会返回true。(instanceof只适用于构造函数创建返回的复杂对象和实例。)
  • 用instanceof检测undefined和null是不是Object实例时,返回false。
    function Person(){}
function Student(){}
Student.prototype = new Person();
var John = new Student();
console.log(John instanceof Student); // true
console.log(John instancdof Person); // true
console.log(John instancdof Object); // true
var a;


用instanceof检测undefined和null是不是Object实例时,返回false。
typeof a; //"undefined"
a instanceof Object; //false
var b = null;
typeof b; //"object"
b instanceof Object; //false


使用constructor检测

 ​