您现在的位置:首页 >> 前端 >> 内容

typeof与instanceof操作符的使用教程

时间:2017/11/9 9:20:42 点击:

  核心提示:typeof与instanceof都是用来检测变量类型的,不同的是,typeof用来检测基本数据类型,instanceof用来检测引用类型一 . typeof操作符typeof操作符是确定一个变量是字...

typeof与instanceof都是用来检测变量类型的,不同的是,typeof用来检测基本数据类型,instanceof用来检测引用类型

一 . typeof操作符

typeof操作符是确定一个变量是字符串、数值、布尔值、还是undefined的最佳工具

对一个值使用typeof操作符可能返回下列某个字符串

1.”undefined”—— 如果这个值未定义

var message;

console.log(typeof message);   // "undefined"

2.”boolean”—— 如果这个值是布尔值

console.log(typeof true);      // "boolean"
console.log(typeof false);     // "boolean"

3.”string”—— 如果这个值是字符串

console.log(typeof '123');     // "string"

4.”number”—— 如果这个值是数值

console.log(typeof 123.123);   // "number"
console.log(typeof 123);       // "number"

5.”object”—— 如果这个值是对象或null

console.log(typeof null);      // "object"

var obj = new Object();
console.log(typeof obj);       // "object"

6.”function”—— 如果这个值是函数

var func = function () {
    return true;
};

console.log(typeof func);     // "function"

二 . instanceof

instanceof可以检测一个对象是什么类型的对象

如果变量是给定引用类型的实例,那么instanceof操作符就会返回true

function Person(name, job) {
    this.name = name;
    this.job = job;
}

var person = new Person("john", "doctor");

alert(person instanceof Person);    // true
alert(person instanceof Object);    // true

根据规定,所有引用类型的值都是Object对象的实例。因此在检测一个引用类型和Object构造函数时,instanceof操作符始终会返回true,如果使用instanceof操作符检测基本类型的值,则该操作符始终会返回false

Tags:TY YP PE EO 
作者:网络 来源:......的博客