JS面试题:判断数据类型

135 阅读1分钟

1. typeof

返回一个数据类型

      console.log(typeof 1); // number
      console.log(typeof "123"); // string
      console.log(typeof true); // boolean
      console.log(typeof undefined); // undefined
      console.log(typeof null); // object
      console.log(typeof [1, 2, 3]); // object
      console.log(typeof { a: 1 }); // object
      console.log(
        typeof function () {
          return true;
        }
      ); // function
      console.log(typeof Symbol("test")); // symbol

注意:如果用typeof来判断数据类型,在判断对象,数组,null的时候要注意了,这三个用typeof返回的类型都是对象object

如果要用typeof来判断一个数据的类型,很明显对象,数组,还有null无法区分类型

2. Object.prototype.toString.call

    console.log(Object.prototype.toString.call(1)) // [object Number]
    console.log(Object.prototype.toString.call('123')) // [object String]
    console.log(Object.prototype.toString.call(true)) // [object String]
    console.log(Object.prototype.toString.call(undefined)) // [object Undefined]
    console.log(Object.prototype.toString.call(null)) // [object Null]
    console.log(Object.prototype.toString.call([1, 2, 3])) // [object Array]
    console.log(Object.prototype.toString.call({ a: 1 })) // [object Object]
    console.log(Object.prototype.toString.call(function () {
      return true;
    })) // [object Function]

上面用typepf来判断数据类型,很明显无法具体区分对象,数组,null这三个,所以这边要想完整判断所有数据的类型都通用,则用 Object.prototype.toString.call这个方法来