変数のデータ型を正確に判断する方法

上記の問題を解決する前に、基本的な知識を理解する必要があります

JSデータ型には、undefined、null、boolean、number、stringの5つの基本型があります。

複雑なデータ型、オブジェクトもあります

保管方法から、それは値タイプ、参照タイプに分けられ、オブジェクトは参照タイプです。

タイプの

この演算子は値タイプのデータタイプのみを決定できます。参照タイプは特に細分できません

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

上記のコードでは、null、配列、オブジェクト、および正規表現はすべて出力オブジェクトですが、関数typeofは区別されますが、関数は値型ではありません。関数はまだオブジェクトですが、関数のステータスは非常に高くなっています。言語は、typeofが関数を区別できるように設計されています。

問題は、オブジェクトのデータ型をどのように細分するかということです。

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;
}

上記のコードは理解するのが難しくないはずなので、詳細には説明しません。関数の精度をテストしてください

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(){}) ) 

もちろん、上記の関数はセット、マップ、その他のオブジェクトを判断できません。出力はまだオブジェクトです。

おすすめ

転載: www.cnblogs.com/tourey-fatty/p/12721449.html