判定类型
2010-01-21 21:13:35 来源:WEB开发网核心提示:目前最精确的判定方法(不包括自定义类型)1.var is = function (obj, type) { 2.var _toString = Object.PRototype.toString,undefined; 3.return (type === "Null" && obj === null
目前最精确的判定方法(不包括自定义类型)
1.var is = function (obj, type) {
2.
var _toString = Object.PRototype.toString,undefined;
3.
return (type === "Null" && obj === null) ||
4.
(type === "Undefined" && obj === undefined ) ||
5.
_toString.call(obj).slice(8,-1) === type;
6.};
用法如下:
01.//***************示例一,判定数组与函数
02.
var forEach = function(array,fn,bind){
03.
if(is(array,"Array") && is(Array.forEach,"Function")){
04.
array.forEach(fn,bind);
05.
}else{
06.
for(var i=0,n=array.length;i<n;i++){
07.
i in array && fn.call(bind,array[i],i,array)
08.
}
09.
}
10.
}
11.//***************示例二,判定null
12.var a = null
13.alert(is(a,"Null"))
14.//***************示例二,判定undefined
15.var b
16.alert(is(b,"Undefined"))
另一个变种,直接返回表示类型的字符串
1.var getType = function (obj) {
2.
var _toString = Object.prototype.toString,undefined;
3.
return obj === null? "Null":
4.
obj === undefined ? "Undefined":
5.
_toString.call(obj).slice(8,-1);
6.};
用法:
01.var arr = [1,2,3,4]
02.
alert(getType(arr));//Array
03.
var nil = null
04.
alert(getType(nil))//Null
05.
var und ;
06.
alert(getType(und))//Undefined
07.
var spans = document.getElementsByTagName("span");
08.
alert(getType(spans)) //HTMLCollection
09.
alert(getType(spans[0].childNodes))//NodeList
1.var is = function (obj, type) {
2.
var _toString = Object.PRototype.toString,undefined;
3.
return (type === "Null" && obj === null) ||
4.
(type === "Undefined" && obj === undefined ) ||
5.
_toString.call(obj).slice(8,-1) === type;
6.};
用法如下:
01.//***************示例一,判定数组与函数
02.
var forEach = function(array,fn,bind){
03.
if(is(array,"Array") && is(Array.forEach,"Function")){
04.
array.forEach(fn,bind);
05.
}else{
06.
for(var i=0,n=array.length;i<n;i++){
07.
i in array && fn.call(bind,array[i],i,array)
08.
}
09.
}
10.
}
11.//***************示例二,判定null
12.var a = null
13.alert(is(a,"Null"))
14.//***************示例二,判定undefined
15.var b
16.alert(is(b,"Undefined"))
另一个变种,直接返回表示类型的字符串
1.var getType = function (obj) {
2.
var _toString = Object.prototype.toString,undefined;
3.
return obj === null? "Null":
4.
obj === undefined ? "Undefined":
5.
_toString.call(obj).slice(8,-1);
6.};
用法:
01.var arr = [1,2,3,4]
02.
alert(getType(arr));//Array
03.
var nil = null
04.
alert(getType(nil))//Null
05.
var und ;
06.
alert(getType(und))//Undefined
07.
var spans = document.getElementsByTagName("span");
08.
alert(getType(spans)) //HTMLCollection
09.
alert(getType(spans[0].childNodes))//NodeList
- ››判定类型
- ››类型转化与final修饰符
更多精彩
赞助商链接