判断一个对象是否属于某个类型

  • Object.prototype.toString.call();
  • 对于 Object 对象,直接调用 toString() 就能返回 [object Object] 。而对于其他对象,则需要通过 call / apply 来调用才能返回正确的类型信息。
function getType(value) {
    
    
    if(typeof value !== 'object') {
    
    
        return typeof value;
    } else {
    
    
        return Object.prototype.toString.call(value).split(' ')[1].slice(0, -1);
    }
};
console.log( getType() );  // undefined
console.log( getType(null) );  // Null
console.log( getType(123) );  // number
console.log( getType('温情') );  // string
console.log( getType({
    
    }) );  // Object
console.log( getType([]) );  // Array
console.log( getType(new Date) );  // Date
console.log( getType(new RegExp) );  // RegExp
console.log( getType(new Function) );  // function

猜你喜欢

转载自blog.csdn.net/qq_48960335/article/details/123707662