js的数据类型
js数据分为两种类型:原始数据类型和引用数据类型。
- 原始数据类型有:string、number、boolean、undefined和null
- 引用数据类型有:Function、Object、Date、RegExp、Number、String、Boolean和自定义类等
js类型判断
- typeof()函数
- instanceof
- Object.prototype.toString.call()
- constructor
1,typeof()判断
对于原始数据类型,我们可以使用typeof()函数来判断他的数据类型:
typeof(1) //number
typeof("1") //string
typeof(true) //boolean
typeof(undefined) //undefined
typeof(null) //object
注释:您也许会问,为什么 typeof 运算符对于 null 值会返回 “object”。这实际上是 JavaScript 最初实现中的一个错误,然后被 ECMAScript 沿用了。现在,null 被认为是对象的占位符,从而解释了这一矛盾,但从技术上来说,它仍然是原始值。
2,instanceof
–因为所有的引用数据类型都会返回"object”。
var obj = {};
obj instanceof Object; //true
var arr = [];
arr instanceof Array; //true
var now = new Date();
now instanceof Date; //true
var func = function(){};
func instanceof Function; //true
var str = "string";
str instanceof String; //false
3、Object.prototype.toString.call()
var num1 = 1;
var num2 = new Number(1);
Object.prototype.toString.call(num1) == "[object Number]"; //true
Object.prototype.toString.call(num2) == "[object Number]"; //true
var arr = [];
Object.prototype.toString.call(arr) == "[object Array]"; //true
var func = function(){};
Object.prototype.toString.call(func) == "[object Function]"; //true
function A(){};
var a = new A();
Object.prototype.toString.call(a) == "[object Object]"; //true
4、constructor
console.log([].constructor == Array);
console.log({}.constructor == Object);
console.log("string".constructor == String);
console.log((123).constructor == Number);
console.log(true.constructor == Boolean);
另外附上较为严谨的判断数组Array的方法:
function isArray(object){
return object && typeof object==='object' &&
Array == object.constructor;
}
通用判断函数类型:
var valide = (function(){
// 是否是字符串
function isString(value){
return Object.prototype.toString.call(value) == "[object String]";
}
// 是否是数字
function isNumber(value){
return Object.prototype.toString.call(value) == "[object Number]";
}
// 是否是布尔值
function isBoolean(value){
return Object.prototype.toString.call(value) == "[object Boolean]";
}
// 是否undefined
function isUndefined(value){
return Object.prototype.toString.call(value) == "[object Undefined]";
}
// 是否是null
function isNull(value){
return Object.prototype.toString.call(value) == "[object Null]";
}
// 是否数组
function isArray(value){
return Object.prototype.toString.call(value) == "[object Array]";
}
// 是否是函数
function isFunction(value){
return Object.prototype.toString.call(value) == "[object Function]";
}
// 是否是对象
function isObject(value){
return Object.prototype.toString.call(value) == "[object Object]";
}
// 是否是正则表达式
function isRegExp(value){
return Object.prototype.toString.call(value) == "[object RegExp]";
}
// 是否是日期对象
function isDate(value){
return Object.prototype.toString.call(value) == "[object Date]";
}
return {
isString: isString,
isNumber: isNumber,
isBoolean: isBoolean,
isUndefined: isUndefined,
isNull: isNull,
isArray: isArray,
isFunction: isFunction,
isObject: isObject,
isRegExp: isRegExp,
isDate: isDate
};
})();