JS六大基本類型:number,String,object,Boolean,null, undefined
數據類型判斷 typeof
只能判斷number,String,boolean, undefined。其余的全部返回Object類型批什。
數組判斷
- instanceof
判斷對象必須事先聲明
var a = [1,2,3];
consosle.log(a instanceof Array);
- constructor 返回對創(chuàng)建此對象的函數的引用.
判斷對象必須事先聲明
var a = [1,2,3];
console.log(a.constructor == Array);//true or false
console.log([].constructor == Array);
console.log({}.constructor == Object);
console.log("string".constructor == String);
console.log((123).constructor == Number);
console.log(true.constructor == Boolean);
//嚴謹判斷方法
function isArray(object){
return object && typeof object ==='object' && Array == object.constructor
}
- 特性判斷法
object. propertyIsEnumerable(proName)
判斷指定的屬性是否可列舉
備注:如果 proName 存在于 object 中且可以使用一個 For…In 循環(huán)窮舉出來隆判,那么 propertyIsEnumerable 屬性返回 true墙懂。如果 object 不具有所指定的屬性或者所指定的屬性不是可列舉的诈悍,那么 propertyIsEnumerable 屬性返回 false砰碴。
propertyIsEnumerable 屬性不考慮原型鏈中的對象扮授。
eg:
var a = new Array("apple", "banana", "cactus");
document.write(a.propertyIsEnumerable(1));
- 最簡單判斷方法
function isArray(o) {
return Object.prototype.toString.call(o) === ‘[object Array]‘;
}
完整類型判斷方法
function typeOf(value) {
if (null === value) {
return 'null';
}
var type = typeof value;
if ('undefined' === type || 'string' === type) {
return type;
}
var typeString = Object.prototype.toString.call(value);
switch (typeString) {
case '[object Array]':
return 'array';
case '[object Date]':
return 'date';
case '[object Boolean]':
return 'boolean';
case '[object Number]':
return 'number';
case '[object Function]':
return 'function';
case '[object RegExp]':
return 'regexp';
case '[object Object]':
if (undefined !== value.nodeType) {
if (3 == value.nodeType) {
return (/\S/).test(value.nodeValue) ? 'textnode': 'whitespace';
} else {
return 'element';
}
} else {
return 'object';
}
default:
return 'unknow';
}
}
文章摘抄:
js數據類型判斷和數組判斷
通過 Object.prototype.toString.call() 進行類型判斷