js 数据类型的判断

1. typeof 运算符

  typeof 可以判断基本数据类型:

  typeof 123; // "number"

  typeof 'abc'; // "string"

  typeof true; // "boolean"

  碰到复合数据类型的情况:

  typeof {}; // "object"

  typeof []; // "object"

  var f = function(){};

  typeof f; //'function'

  

  特殊情况:

  1.typeof null; // "object" 这是历史遗留问题,不做深究,是个隐藏的坑

  2. typeof undefined; (undefined指未定义的变量)// “undefined” 

  利用这个特点 用于判断语句

if (v) {
  // ...
}
// ReferenceError: v is not defined

// 正确的写法
if (typeof v === "undefined") {
  // ...
}

综上,利用typeof 得到值就有"number","string","boolean","object","function","undefined" 这6个值

2. instanceof 运算符

  对于对象和数组这种数据,利用typeof不能区分,这时候需要用到instanceof 运算符

var o = {};
var a = [];

o instanceof Array // false
a instanceof Array // true

猜你喜欢

转载自www.cnblogs.com/ikumi/p/11309772.html