js 数据类型的判断

2022-10-17,,

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

 

《js 数据类型的判断.doc》

下载本文的Word格式文档,以方便收藏与打印。