js 类型检测(typeof进行检测)

1.js中的基本类型:

字符串、数字、布尔、对象、Null、Undefined。而对象是个比较复杂的类型,其中又可以分为数组,函数与对象

2.检测

利用typeof来进行数据类型检测。它可以检测出来的数据类型有:string,number,boolean,function,undefined,object。数组,null与{}经过其转换后返回值都为object。所以重点就是怎么区分数组,null与{}

代码如下:

 function typeTest (obj) {
    var result = typeof obj
	if (result === 'object') {  // object
	    if (Array.isArray(obj)) { // 区分数组
            console.log('array')
		} else {
			for (var item in obj) { // 区分有属性的对象
			 	console.log('object')
			 	return false
			 } 
			 if (!obj) { // 区分null
			 	console.log('null')
			 } else { // 区分{}
			 	console.log('{}')
			 }
		}
	} else {
		console.log(result) // 基本类型
	    }
    }

检测:

typeTest('111') // string
typeTest(123) // number
typeTest(true) // boolean
typeTest(typeTest) // function
typeTest(undefined) // undefined
typeTest(NaN) // number
			 
typeTest([1,2]) // array
typeTest({'a': 1, 'b': 2}) // object
typeTest(null) // null
typeTest({}) // {}

检测数据是否有值的小工具(检测的类型包括:字符串,数字,对象,数组;返回布尔值):

	function isValue (variable) {
				var typeStr = typeof variable;
				if (typeStr === 'object') {
					if (Array.isArray(variable)) { // 数组
						return Boolean(variable.length);
					} else {
						for (var item in variable) { // 有属性的对象
							return true;
						} 
						return false; // {}或者null的情况
					}
				} else {
					return Boolean(variable);
				}
			}

猜你喜欢

转载自blog.csdn.net/weixin_42011096/article/details/82833114