小tips:JS中typeof与instanceof用法

介绍

typeof

typeof用以获取一个变量或者表达式的类型,typeof一般只能返回如下几个结果:

  • number
  • boolean
  • string
  • function(函数)
  • object(NULL,数组,对象)
  • undefined。

例子:

function curFun(){};
var numberType = 123;
var stringType = "123";
var booleanType = false;
var obj = {};
var nullType = null;
var arrayType = [];
var unden;

console.log(typeof curFun); //function

console.log(typeof numberType);//number
console.log(typeof stringType);//string
console.log(typeof booleanType); //boolean

console.log(typeof obj); //object
console.log(typeof nullType); //object
console.log(typeof arrayType); //object

console.log(typeof unden); //undefined

我们可以使用typeof来获取一个变量是否存在,如if(typeof a!="undefined"){},而不要去使用if(a)因为如果a不存在(未声明)则会出错,

正因为typeof遇到null,数组,对象时都会返回object类型,所以当我们要判断一个对象是否是数组时或者判断某个变量是否是某个对象的实例则要选择使用另一个关键语法instanceof

instanceof

instanceof用于判断一个变量是否某个对象的实例

var arr = new Array();
console.log(arr instanceof Array); //true
console.log(arr instanceof Object) //true,因为Array是object的子类
function test(){};
var testInstance = new test();
console.log(testInstance instanceof test); //true

js判断变量是否未定义的代码

一般如果变量通过var声明,但是并未初始化的时候,变量的值为undefined,而未定义的变量则需要通过 "typeof 变量"的形式来判断,否则会发生错误。
实际应用:
variable有的页面我们不定义,但有的页面定义了,就可以需要这样的判断方法,没有定义的就不执行。

if("undefined" != typeof variable){ 
    if(variable=="abc"){ 
        console.log('成功'); 
    } 
}

 

posted @ 2017-09-12 16:34  风雨后见彩虹  阅读(427)  评论(0编辑  收藏  举报