关于判断类型的方法

老问题:关于判断类型的方法:

  1. typeof:这个很常用也很好用,缺点是当变量是对象时,这个方法无法精确区分到底是哪一种对象,比如 
array,function,String,Number,Boolean都有可能:

var a = new String("abc");
  var b = function(){};
  var c = [];
  alert(typeof a)    //object
  alert(typeof b)    //object
  alert(typeof c)    //object

   当然,如果你只需要区分基本数据类型还是可以的。

  2:instanceof: 这个方法是判断变量是否是某个构造对象的实例:  

  var c = [];
  alert(c instanceof Array)    //true

   当然通过constructor也可以判断,读者可以自己尝试。

  3:利用Object.prototype.toString;  

function get_type (obj) {
return obj === null ? 'null' : (obj === undefined ? 'undefined' : Object.prototype.toString.call(obj).slice(8, -  
1).toLowerCase()); //返回这样的字符 截取后获得类型[object Array]
posted @ 2012-08-05 23:43  allexwang  阅读(255)  评论(0编辑  收藏  举报