JS判断数据类型方法以及封装方法实现检查数据类型;

**1. typeof **

 console.log( typeof(1) );//number
 
 console.log( typeof "abc" );//string

console.log(typeof false); //boolean

console.log(typeof function () {
    
    }); //function

console.log(typeof {
    
    }); //object

console.log(typeof undefined); //undefined
		//typeof无法判断出数组、对象、null的具体类型,

2.instanceof

 console.log( [1,2,3]  instanceof  Array);//true
 
 console.log( {
    
    "name":"a"}  instanceof Array );//false
 
 console.log( "abcde" instanceof String );//false

  

**

3.Object.prototype.toString.call

**

console.log(    Object.prototype.toString.call( "234" )  );//string
	
console.log(    Object.prototype.toString.call( null )  );//null
	
console.log(    Object.prototype.toString.call( [1] )  );//Array

4.封装函数检测数据类型;

 function checkType( date){
    
    
            var type=Object.prototype.toString.call(date);
            type= type.substr( 8,type.length-9 );
            return type;
        };

        var x=checkType(1);
        console.log(x);//number

猜你喜欢

转载自blog.csdn.net/w1666793979/article/details/111396771