js使用typeof与instanceof相结合编写一个判断常见变量类型的函数
/**
* 常见类型判断
* @param {any} param
*/
function getParamType(param) {
// 先判断是否能用typeof 直接判断
let types1 = ['number', 'string', 'boolean', 'undefined', 'symbol', 'function']
let type = typeof param;
type = types1.indexOf(type);
if (type !== -1) {
return types1[type]
}
// 剩余的用instanceof判断
switch (true) {
case param instanceof Date:
return 'date'
case param instanceof Array:
return 'array'
case param instanceof Object:
return 'object'
case null === param && !param:
return 'null'
default:
return 'can not judge'
}
}
console.log(getParamType(1)); // number
console.log(getParamType('1')); // string
console.log(getParamType(true)); // boolean
console.log(getParamType(undefined)); // undefined
console.log(getParamType(Symbol.for(2))); // symbol
console.log(getParamType(() => 1)); // function
console.log(getParamType([])); // array
console.log(getParamType({})); // object
console.log(getParamType(new Date())); // date
console.log(getParamType(null)); // null
"你的指尖,拥有改变世界的力量! "
欢迎关注我的个人博客:https://sugarat.top