js type judgment

I have encountered an interview question before that needs to determine whether it is a string or a number.

After thinking about it, typeof() can still do it, but typeof() is not omnipotent, and I can't tell the difference between an array and an object. I encapsulated a simple type judgment method myself, record it, and use it later. take away for use;

 
It can determine the specific type, array || object || function || boolean || null || string || number which of these types,

function isType(obj){
va    r type = typeof(obj);
if(type!=='object'){
return type;
}else if(!obj){
return 'null';
}else if(Array.isArray(obj)===true){
return 'array';
}else{
return type;
}

}

It is also good to pass another one for judgment when passing parameters;

function isType(obj,str){
var type = typeof(obj);
if(!obj){
type = 'null';
}else if(Array.isArray(obj)===true){
type = 'array';
}
if(str&&str===type){
return true;
}else if(str&&!str===type){
return false;
}
return type;

}

That is, the effect of judging the type can be achieved, and it can be directly compared

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326053051&siteId=291194637