xianzao / xianzao-interview

前端 每日一道面试题
64 stars 4 forks source link

【2022.12.12】数据类型判断 #16

Open xianzao opened 1 year ago

xianzao commented 1 year ago

类型判断在 web 开发中有非常广泛的应用:

  1. 判断数字还是字符串;
  2. 判断数组还是对象;
  3. 判断日期、正则、错误类型;
  4. 判断 plainObject、空对象、Window 对象;

请介绍你对数据类型的理解

xianzao commented 1 year ago

1. typeof

最常用的就是 typeof

console.log(typeof('xianzao')) // string

typeof 是一元操作符,放在其单个操作数的前面,操作数可以是任意类型。返回值为表示操作数类型的一个字符串。

在 ES6 前,JavaScript 共六种数据类型,分别是:

Undefined、Null、Boolean、Number、String、Object

然而当我们使用 typeof 对这些数据类型的值进行操作的时候,返回的结果却不是一一对应,分别是:

undefined、object、boolean、number、string、object

注意以上都是小写的字符串。Null 和 Object 类型都返回了 object 字符串。

这里可以发现,typeof 却能检测出函数类型:

function a() {}

console.log(typeof a); // function

所以 typeof 能检测出六种类型的值,但是,除此之外 Object 下还有很多细分的类型呐,如 Array、Function、Date、RegExp、Error 等。

如果用 typeof 去检测这些类型:

var date = new Date();
var error = new Error();
console.log(typeof date); // object
console.log(typeof error); // object

返回的都是 object 呐,可以看到,针对object的细分,typeof是没法分别的;

2. Object.prototype.toString

When the toString method is called, the following steps are taken:

If the this value is undefined, return "[object Undefined]". If the this value is null, return "[object Null]". Let O be the result of calling ToObject passing the this value as the argument. Let class be the value of the [[Class]] internal property of O. Return the String value that is the result of concatenating the three Strings "[object ", class, and "]".

翻译下来就是:

当 toString 方法被调用的时候,下面的步骤会被执行:

如果 this 值是 undefined,就返回 [object Undefined] 如果 this 的值是 null,就返回 [object Null] 让 O 成为 ToObject(this) 的结果 让 class 成为 O 的内部属性 [[Class]] 的值 最后返回由 "[object " 和 class 和 "]" 三个部分组成的字符串

通过规范,我们至少知道了调用 Object.prototype.toString 会返回一个由 "[object " 和 class 和 "]" 组成的字符串,而 class 是要判断的对象的内部属性。

console.log(Object.prototype.toString.call(undefined)) // [object Undefined]
console.log(Object.prototype.toString.call(null)) // [object Null]

var date = new Date();
console.log(Object.prototype.toString.call(date)) // [object Date]

总共,可以得到14种不同的类型:

// 以下是11种:
var number = 1;          // [object Number]
var string = '123';      // [object String]
var boolean = true;      // [object Boolean]
var und = undefined;     // [object Undefined]
var nul = null;          // [object Null]
var obj = {a: 1}         // [object Object]
var array = [1, 2, 3];   // [object Array]
var date = new Date();   // [object Date]
var error = new Error(); // [object Error]
var reg = /a/g;          // [object RegExp]
var func = function a(){}; // [object Function]

function checkType() {
    for (var i = 0; i < arguments.length; i++) {
        console.log(Object.prototype.toString.call(arguments[i]))
    }
}

checkType(number, string, boolean, und, nul, obj, array, date, error, reg, func)

除了以上 11 种之外,还有:

console.log(Object.prototype.toString.call(Math)); // [object Math]
console.log(Object.prototype.toString.call(JSON)); // [object JSON]

除了以上 13 种之外,还有:

function a() {
    console.log(Object.prototype.toString.call(arguments)); // [object Arguments]
}
a();

所以我们可以识别至少 14 种类型,当然我们也可以得到,[[class]] 属性至少有 12 个。

3. type API

Q:写一个 type 函数能检测各种类型的值,如果是基本类型,就使用 typeof,引用类型就使用 toString。此外鉴于 typeof 的结果是小写,所以所有的结果都是小写。

考虑到实际情况下并不会检测 Math 和 JSON,所以去掉这两个类型的检测。

我们来写一版代码:

// 第一版
var class2type = {};

// 生成class2type映射
"Boolean Number String Function Array Date RegExp Object Error Null Undefined".split(" ").map(function(item, index) {
    class2type["[object " + item + "]"] = item.toLowerCase();
})

function type(obj) {
    return typeof obj === "object" || typeof obj === "function" ?
        class2type[Object.prototype.toString.call(obj)] || "object" :
        typeof obj;
}

但是,在 IE6 中,null 和 undefined 会被 Object.prototype.toString 识别成 [object Object],所以生成第二版:

// 第二版
var class2type = {};

"Boolean Number String Function Array Date RegExp Object Error".split(" ").map(function(item, index) {
    class2type["[object " + item + "]"] = item.toLowerCase();
})

function type(obj) {
    if (obj == null) {
        return obj + "";
    }
    return typeof obj === "object" || typeof obj === "function" ?
        class2type[Object.prototype.toString.call(obj)] || "object" :
        typeof obj;
}

4.1. isFunction

有了 type 函数后,我们可以对常用的判断直接封装,比如 isFunction:

function isFunction(obj) {
    return type(obj) === "function";
}

4.2. 数组

jQuery 判断数组类型,旧版本是通过判断 Array.isArray 方法是否存在,如果存在就使用该方法,不存在就使用 type 函数。

var isArray = Array.isArray || function( obj ) {
    return type(obj) === "array";
}

但是在 jQuery v3.0 中已经完全采用了 Array.isArray。所以建议直接使用Array.isArray判断数组