小tips:JS中typeof与instanceof用法
2017-09-12 16:34
411 查看
介绍
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('成功'); } }
相关文章推荐
- js中typeof与instanceof用法区别
- js中typeof和instanceof用法区别
- JS中typeof和instanceof的用法小解
- js中typeof和instanceof用法区别
- js中typeof和instanceof用法区别
- js中typeof和instanceof用法区别
- js中typeof与instanceof的不同用法
- JS中typeof和instanceof的用法和区别
- js中的typeof和instanceof的用法和区别(附类型判断方法)
- js中typeof与instanceof用法的区别
- JavaScript中instanceof运算符的用法以及和typeof的区别
- JS中typeof与instanceof之间的区别总结
- js中typeof的用法详解
- javascript中typeof和instanceof 的用法区别
- JS中的instanceof和typeof
- JS中的instanceof和typeof
- JS中typeof与instanceof之间的区别总结
- JS中typeof和instanceof的区别
- JavaScript高级程序设计(五): js的关键字instanceof和typeof使用
- JS中typeof与instanceof的区别