JavaScript之类型判断

好久没有写博客了,现在重新开始。今天写的是一个关于JavaScript类型判断的问题


JavaScript判断类型常见的是有四种方法——typeof,toString,instanceof和constructor

本次主要说typeof和toString

type

typeof用于区分对象和原始类型

基本类型

function test(o){
    console.log(typeof o)
}
test(undefined);
test(null);
test(3);
test("Sadf");
test({});
test(true)
运行结果为


可以看到,typeof在基本类型上除了null还是不错的


其它类型

// Symbols
typeof Symbol() === 'symbol'
typeof Symbol('foo') === 'symbol'
typeof Symbol.iterator === 'symbol'


// Undefined
typeof undefined === 'undefined';
typeof declaredButUndefinedVariable === 'undefined';
typeof undeclaredVariable === 'undefined'; 


// Objects
typeof {a: 1} === 'object';

// use Array.isArray or Object.prototype.toString.call
// to differentiate regular objects from arrays
typeof [1, 2, 4] === 'object';

typeof new Date() === 'object';


// The following is confusing. Don't use!
typeof new Boolean(true) === 'object'; 
typeof new Number(1) === 'object'; 
typeof new String('abc') === 'object';


// Functions
typeof function() {} === 'function';
typeof class C {} === 'function';
typeof Math.sin === 'function';


可以看到,typeof在面对sybol时显示sybol,面对function,class时显示function,剩下时候都是显示object(尤其是数组和包装类,严重影响使用)


下面让我们看看toString的情况


toString

鉴于toString只有对象上才有,所以使用以下调用方式

function toStr(o){
    console.log(toString.call(o))
}

toStr(undefined);
toStr(null);
toStr(3);
toStr("adf");
toStr(true);
toStr(Symbol("adsf"))


这一次返回结果还让人满意,让我们进行更复杂的测试

toString.call(new Date);    // [object Date]
toString.call(new String);  // [object String]
toString.call(Math);        // [object Math]

// Since JavaScript 1.8.5
toString.call(undefined);   // [object Undefined]
toString.call(null);        // [object Null]     
toString.call(()=>{console.log("hello"))        //[object Function]
toString.call(class A{})			//[object Function]
toString.call(new Number("123"))		//[object Number]


可以看到,这一次结果还是很满意的(除了class,不过在JavaScript中class只是一个function的语法糖)




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值