Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

【JavaScript Basis】编写个获取数据类型的Fn #6

Open
qixMan opened this issue Sep 10, 2015 · 0 comments
Open

【JavaScript Basis】编写个获取数据类型的Fn #6

qixMan opened this issue Sep 10, 2015 · 0 comments

Comments

@qixMan
Copy link
Owner

qixMan commented Sep 10, 2015

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 中的具体类型,没有很详尽。
例如

typeof null; // "object"
typeof []; //"object"
typeof /\b/;// "object"

显然这满足不了你,在工作场景里,检测数据类型是不是array还是很常见的。
当然常用的解决办法是使用 instanceof.

instanceof

instanceof 需要两个参数,一前一后,前者是待检测数据,后者是类型构造函数,返回一个boolean,表示前者是否是后者的实例。

利用这个关键字,也可以达到一些检测数据类型的目的。例如在上面一段提到的typeof不能很好检测的array类型。可以用instanceof 来检测

[1,2,3] instanceof Array;// true

不过这样检测也是太双标了,还得 typeof 和 instanceof 结合着种。

不如自己写个util fn,一步到位。

一步到位的类型检测

这里的关键在于 obj 的 toString方法,这个方法会返回具体类型,然后我们根据这个类型,使用正则处理一下,就可得出想要结果。

需要注意的是只有 obj 的 toString 可以实现这个效果,所以数据如果是别的类型,需要 call 一下这个 obj 的 toString,而不能直接使用自身所带有的 toString.

//key point is the toString method of Object.
const type = data => {
  return typeof data != "object" ?
         typeof data             :
         {}.toString.call(data).match(/\w+/g).pop().toLowerCase();
}

//test cases
const assert = 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(/^$/));
  });
});
@qixMan qixMan changed the title 《IT创业疯魔史》 摘选 【JavaScript Basis】编写个获取数据类型的Fn Sep 5, 2016
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant