【JS八股文】数据类型的判断

170 阅读2分钟

由于JS中变量没有类型,只有值才有,所以当我们拿到一个变量,想要知道他的类型的话,需要用到一些方法。

typeof

typeof可以得到变量持有值的类型。
返回值:值类型对应的字符串。

  • 适合基本类型function的检测
  • 遇到null失效
// typeof适合的场景 (基本类型 和 function)
console.log(typeof number);  // number

console.log(typeof string); // string

console.log(typeof boolean); // boolean

console.log(typeof Symbol()); // symbol

console.log(typeof undefined); // undefined

console.log(typeof function a() {  }); // function

// typeof不适合的场景 (除function外的对象类型)
console.log(typeof []); // object

console.log(typeof {}); // object


// typeof检测让人困惑的两种情况
console.log(typeof null); // object
// 语言本身的bug,但null是基本类型

console.log(typeof NaN); // number
// NaN(not a number)更准确的解释为一个 坏的数字 或 无效数字
// NaN为number类型的一个值(与 1、2、3一样是个数值)
// 例:Number('str'); // NaN

tips: 可以利用typeof null === 'object'的特性实现一个变量是否为null的判断

var a = null;

if (!a && typeof a === 'object') {
  // 可判断a为null
}; 

instanceof

instanceof用来判断操作符的左边的对象类型变量(基本类型结果都为false),是否是右边的函数构造系
返回值:true或false

  • 适合对象类型自定义构造函数
  • 操作符的左边应为对象类型([]、{}...)
  • 操作符的右边应为函数构造系(若不是会抛出Type Error异常)
  • 基于原型链去判断的操作符(会判断左边对象原型链上是否有右边构造函数
// 原生对象判断
({num1: 1}) instanceof Object; //true

[1,2] instanceof Array; //true

[1,2] instanceof Object; // true  回顾:Object是所有对象原型链的顶端
// 自定义对象判断
function Smile() {
  this.num1 = 1;
}

var haha = new Smile;

haha instanceof Smile; // true;

Object.prototype.toString

Object.prototype.toString利用JS中对象的toString方法来对数据进行判断。
返回值:'[object 数据类型]'(字符串)

  • 适合对象类型基本类型(不适合自定义构造函数
  • ie6/7/8nullundefined的判断失效
Object.prototype.toString.apply(1); // '[object Number]'

Object.prototype.toString.apply('s'); // '[object String]'

Object.prototype.toString.apply(true); // '[object Boolean]'

Object.prototype.toString.apply([]); // '[object Array]'

Object.prototype.toString.apply({}); // '[object Object]'

Object.prototype.toString.apply(function(){});  // '[object Function]'

// 在ie6/7/8中返回'[object Object]'
Object.prototype.toString.apply(null); // '[object Null]'

Object.prototype.toString.apply(undefined); // '[object Undefined]'

如果觉得内容对你有帮助,请点个关注,你们的鼓励是我持续更新下去的动力,比心。

如需转载请注明出处,感恩。

更多内容可先关注GitHub