JS中typeof与instanceof用法

前端之家收集整理的这篇文章主要介绍了JS中typeof与instanceof用法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

介绍

typeof

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

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

例子:

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

console.log(typeof curFun); //function

console.log(typeof numberType);number
console.log(typeof stringType);string
console.log(typeof booleanType); boolean
typeof obj); object
console.log(typeof nullType); typeof arrayType); object
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的子类
 test(){};
var testInstance =  test();
console.log(testInstance instanceof test); true

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

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

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

 

猜你在找的JavaScript相关文章