js判斷數(shù)據(jù)類型的方法
一床牧、typeof方法
1计寇、可以判斷數(shù)據(jù)類型,它返回表示數(shù)據(jù)類型的字符串(返回結果只包括number,boolean,string,function,object,undefined);
2博脑、可以使用typeof判斷變量是否存在(如if(typeof a!=“undefined”){…})添履;
3屁倔、Typeof 運算符的問題是無論引用的對象是什么類型 它都返回object
<script>
console.log(
typeof 100, //"number"
typeof 'abc', //"string"
typeof false, //"boolean"
typeof undefined, //"undefined"
typeof null, //"object"
typeof [1, 2, 3], //"object"
typeof {
a: 1,
b: 2,
c: 3
}, //"object"
typeof function() {
console.log('aaa');
}, //"function"
)
</script>
運行結果
typeof.png
二、instanceof方法
一般用來檢測引用數(shù)據(jù)類型暮胧,表達式為:A instanceof B锐借,判斷A是否是B的實例,如果 A 是 B 的實例往衷,則返回 true,否則返回 false钞翔,由構造類型判斷出數(shù)據(jù)類型
注意:instanceof主要用于區(qū)分引用數(shù)據(jù)類型,檢測方法是檢測的類型在當前實例的原型鏈上席舍,不太適合用于簡單數(shù)據(jù)類型的檢測
<script>
console.log(
100 instanceof Number, //false
'dsfsf'
instanceof String, //false
false instanceof Boolean, //false
undefined instanceof Object, //false
null instanceof Object, //false
[1, 2, 3] instanceof Array, //true
{
a: 1,
b: 2,
c: 3
}
instanceof Object, //true
function() {
console.log('aaa');
}
instanceof Function, //true
/^[a-zA-Z]{5,20}$/
instanceof RegExp, //true
)
//注意: instanceof 后面一定要是對象類型布轿,大小寫不能寫錯,該方法適用于一些條件選擇或分支
</script>
運行結果
instanceof.png
三、constructor方法
用于檢測引用數(shù)據(jù)類型汰扭,檢測方法是獲取實例的構造函數(shù)判斷和某個類是否相同稠肘,如果相同則返回true,就說明該數(shù)據(jù)是符合那個數(shù)據(jù)類型的东且,這種方法不會把原型鏈上的其他類也加入進來启具,避免了原型鏈的干擾。
注意:undefined和null沒有constructor屬性珊泳,無法判斷鲁冯。
<script>
var num = 123;
var str = 'abcdef';
var bool = true;
var arr = [1, 2, 3, 4];
var obj = {
name: 'wenzi',
age: 25
};
var fn = function() {
console.log('this is function');
}
var und = undefined;
var nul = null;
var reg = /^[a-zA-Z]{5,20}$/;
// undefined和null沒有constructor屬性
console.log(
num.constructor == Number, //true
str.constructor == String, //true
bool.constructor == Boolean, //true
arr.constructor == Array, //true
obj.constructor == Object, //true
fn.constructor == Function, //true
reg.constructor == RegExp, //true
);
</script>
運行結果
constructor.png
四、Object.prototype.toString.call()方法
適用于所有類型的判斷檢測色查,檢測方法是Object.prototype.toString.call(數(shù)據(jù)) 返回的是該數(shù)據(jù)類型的字符串薯演。
使用Object.prototype.toString.call()的方式來判斷一個變量的類型是最準確的方法。
<script>
var toString = Object.prototype.toString;
console.log(
toString.call(123), //"[object Number]"
toString.call('abcdef'), //"[object String]"
toString.call(true), //"[object Boolean]"
toString.call([1, 2, 3, 4]), //"[object Array]"
toString.call({
name: 'wenzi',
age: 25
}), //"[object Object]"
toString.call(function() {
console.log('this is function');
}), //"[object Function]"
toString.call(undefined), //"[object Undefined]"
toString.call(null), //"[object Null]"
toString.call(/^[a-zA-Z]{5,20}$/), //"[object RegExp]"
)
</script>
運行結果
Object.prototype.toString .png