How to accurately determine the data type of a variable

Before solving the above problem, we need to understand the basic knowledge

There are five basic types of JS data types, undefined, null, boolean, number, string.

There is also a complex data type, object

From the storage method, it is divided into value types, reference types, and object is the reference type.

typeof

This operator can only determine the data type of the value type, the reference type cannot be subdivided specifically

console.log(typeof '123'); // string
console.log(typeof 123); // number
console.log(typeof true); // boolean
console.log(typeof undefined); // undefined
console.log(typeof null); // object
console.log(typeof [1,2]); // object
console.log(typeof {a:1});// object
console.log(typeof /[a]/);// object
console.log(typeof function(){}) // function

In the above code, null, arrays, objects, and regular expressions all output object, but the function typeof is distinguished, but the function is not a value type. The function is still an object, but the status of the function is very high. The language is designed so that typeof can distinguish functions.

So the question is, how to subdivide the data type of object?

function judgeType(item){
  let type = typeof item;

  //判断元素是否为数组
  if(type === 'object'){

  	if(Array.isArray(item)){
  		type = 'array';
  	}else if(item == undefined){
  		type = 'null';
  	}else{
  		const temp = item.toString();

	    if(temp[0] === '/'){
	      type = 'regexp';
	    }
  	}
    
  }

  return type;
}

The above code should not be difficult to understand, so I wo n’t specify it. Test the accuracy of the function

function judgeType(item){
  let type = typeof item;

  //判断元素是否为数组
  if(type === 'object'){

  	if(Array.isArray(item)){
  		type = 'array';
  	}else if(item == undefined){
  		type = 'null';
  	}else{
  		const temp = item.toString();

	    if(temp[0] === '/'){
	      type = 'regexp';
	    }
  	}
    
  }

  return type;
}

console.log(judgeType('123'));
console.log(judgeType(123) );
console.log(judgeType(true) );
console.log(judgeType(undefined) )
console.log(judgeType(null) ) // null
console.log(judgeType([1,2]) ); // array
console.log(judgeType({a:1}) ); // object
console.log(judgeType(/[a]/) ); // regexp
console.log(judgeType(function(){}) ) 

Of course, the above function can not judge Set, Map and other objects, the output is still object.

Guess you like

Origin www.cnblogs.com/tourey-fatty/p/12721449.html