最近在js中发现一个好的方法就是typeof方法,之前没有接触过,但是这次用来之后可以说是爱不释手,首先他的定位精度相当高,在复杂的js语句中显得尤为必要。对于这两天的使用下边来总结一下关于其使用方法。
typeof 运算符把类型信息当作字符串返回。typeof 返回值有六种可能: "number," "string," "boolean," "object," "function," 和 "undefined."我们可以将自己的想要判断的类型作为参数传入typeof方法中举个栗子哈:,if(typeof a!="undefined"){},而不要去使用if(a)因为如果a不存在(未声明)则会出错,对于Array,Null等特殊对象typeof则显得力不从心,因为塔返回的一律为object。
- number:运算数为数字 var x=123 typeof(x) = “number”
- string :运算为字符串 var y="123" typeof(y)="string"
- boolean :运算数字为布尔 var b=true typeof(b) = “boolean”
- object :运算单元为object var x=null ,var x=array typeof(x) = “object”
- function :运算单元为方法:function abc(){} typeof(abc)="fucntion"
typeof 运算符返回一个用来表示表达式的数据类型的字符串。
可能的字符串有:”number”、”string”、”boolean”、”object”、”function” 和 “undefined”。
下边说一下与之类似的instaceof关键字:
举个栗子:
var array=new Array();alert(array instanceof Array);
/**
*这里会返回true
*/
如果下边加上alert(array instanceof Object)也会弹出true
这是因为Array是object的子类,
但是对于一个方法来说,var test=function testfunction(){}
alert(test instanceof testfunction())这里毋庸置疑返回为true.
//得到true并不是因为 Array是Object的子对象,而是因为 Array的prototype属性构造于Object,Array的父级是Function
下边是我的代码实际性应用
if(typeof(_spAreaItem) == 'object'){
if(_spAreaItem.spService.spServiceId == spId){
var _sentity = _spAreaItem.sentity;
for(var m=0;m<_sentity.length;m++){
var _area = _sentity[m];
if(_area.areaId == areaId){
return _area;
}
}
}
}
拓展一下,对于判断js中变量为空的情况非常麻烦,最近就搞了一个方法来判断js中的对象是否为null,undefined,'' 需要时可以直接使用。提高办事效率。分享如下:
function isEmpty(str){
if(str == null){
return true;
}
if(str == undefined){
return true;
}
if(str == ''){
return true;
}
return false;
}