JavaScript数据类型检测

2016-03-09 19:52:56

JavaScript的数据类型分为两类:原始类型(primitive type)和对象类型(object type)。原始类型有5种,分别是:数字(Number)、字符串(String)、布尔值(Boolean)、null和undefined。引用类 型包括:Object、Array、Date、Error、RegExp、Functions。



1.原始类型的检测


对于原始类型中的:数字、字符串、布尔值、undefined,最佳检测方法是使用typeof运算符,typeof检测后会返回一个表示值类型的字符串。typeof的语法是:

typeof <变量>

typeof(<变量>)

对以上4种原始值使用typeof运算符后:数字返回"number" 、    字符串返回"string" 、    布尔值返回"boolean" 、    undefined返回"undefined"。如下:

var str = 'a string';
console.log(typeof str);		//	->	string

var num = 0;
console.log(typeof num);		//	->	string

var bool = true;
console.log(typeof bool);		//	->	boolean

var undefin;
console.log(typeof undefin);		//	->	undefined  未定义的变量和未初始化的变量都将返回undefined

原始值null,应当使用===和!==进行行比较,对null做typeof检测时,返回值为"object"。



2.引用类型的检测


引用值也称做对象(object),在JavaScript中除原始类型外都是引用类型。typeof运算符不能有效检测引用类型,所有引用类型都会返回“object”:

console.log(typeof []);		    //	->	object
console.log(typeof new Date());	    //	->	object
console.log(typeof {});		    //	->	object
console.log(typeof new Error());    //	->	object
console.log(typeof new RegExp());    //	->	object
console.log(typeof Function);    //	->	function

引用类型检测推荐使用instanceof运算符,基本语法是:

value instanceof constructor

对引用类型做instanceof操作:

console.log([] instanceof Array);		//	->	true
console.log(new Date() instanceof Date);        //	->	true
console.log({} instanceof Object);		//	->	true
console.log(new Error() instanceof Error);	//	->	true
var reg = new RegExp();
console.log(reg instanceof RegExp);             //	->	true
function func (argument) {
}
console.log(func instanceof Function)           //	->	true

对于函数做typeof操作返回function,相比intanceof更推荐使用typeof。


对象属性检测

判断属性是否存在最好的方法是使用in运算符,如果属性存在或继承自原型链,都会返回true。如果只想检测对象实例是否存在某属性,而不是从原型继承的属性则使用hasOwnProperty()方法。如下:

function Person() {
    this.name = 'liuht';
    this.doSometing = function() {
	return 'doSometing';
    }
}
Person.prototype.area = 'China';		// 原型链属性

var man = new Person();
man.sex = 'man';

console.log('name' in man);		// 	-> true
console.log('sex' in man);		//	-> true
console.log('area' in man);		//	-> true

console.log(man.hasOwnProperty('name'));		//	-> true
console.log(man.hasOwnProperty('sex'));			//	-> true
console.log(man.hasOwnProperty('area'));			//	-> false

http://itbilu.com/javascript/js/4Jg5yYG.html


你打算打赏多少钱呢?

打赏
(微信扫一扫)