You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
//key point is the toString method of Object.consttype=data=>{returntypeofdata!="object" ?
typeofdata :
{}.toString.call(data).match(/\w+/g).pop().toLowerCase();}//test casesconstassert=require('assert');describe("type",()=>{it("should get right type",()=>{assert.equal("null",type(null));assert.equal("undefined",type(undefined));assert.equal("boolean",type(false));assert.equal("number",type(1));assert.equal("function",type(type));assert.equal("array",type([]));assert.equal("object",type({}));assert.equal("regexp",type(/^$/));});});
The text was updated successfully, but these errors were encountered:
Javascript中的数据类型
Javascript中有6中数据类型。
其中5种是简单类型:
boolean, number, string, undefined, null
还有1种复杂类型 object。
其实我觉得把 null 归为 Object 类型会更容易理解。因为 typeof 对于 null 的返回值是 object,这是一个让初学者很容易懵逼混淆的点。而 null 意为空指针,没有引用,跟 Object 的引用归为一类也能说的过去。
更为细致的划分
对于复杂类型 object,有更为细致的划分,它包含了函数 function,数组 array, 空指针 null,正则表达式 regexp.
typeof
Javascript_中有一个关键字,为_typeof,输入 data,返回一个字符串,显示的是_data type_.
但是它能返回的类型比较粗枝大叶,对于 object 中的具体类型,没有很详尽。
例如
显然这满足不了你,在工作场景里,检测数据类型是不是array还是很常见的。
当然常用的解决办法是使用 instanceof.
instanceof
instanceof 需要两个参数,一前一后,前者是待检测数据,后者是类型构造函数,返回一个boolean,表示前者是否是后者的实例。
利用这个关键字,也可以达到一些检测数据类型的目的。例如在上面一段提到的typeof不能很好检测的array类型。可以用instanceof 来检测
不过这样检测也是太双标了,还得 typeof 和 instanceof 结合着种。
不如自己写个util fn,一步到位。
一步到位的类型检测
这里的关键在于 obj 的 toString方法,这个方法会返回具体类型,然后我们根据这个类型,使用正则处理一下,就可得出想要结果。
需要注意的是只有 obj 的 toString 可以实现这个效果,所以数据如果是别的类型,需要 call 一下这个 obj 的 toString,而不能直接使用自身所带有的 toString.
The text was updated successfully, but these errors were encountered: