javascript 判斷數據類型的幾種方法

<p><strong>javascript 判斷數據類型的幾種方法</strong><br><strong><em>1、typeof 直接返回數據類型字段,可是沒法判斷數組、null、對象</em></strong></p>javascript

typeof 1
"number"

typeof NaN
"number"

typeof "1"
"string"

typeof true
"boolean"

typeof undefined
"undefined"

typeof null
"object"

typeof []
"object"

typeof {}
"object"

<p><strong><em>其中 null, [], {}都返回 "object"</em></strong></p> <p><strong>2、instanceof 判斷某個實例是否是屬於原型</strong></p>java

// 構造函數
function Fruit(name, color) {
    this.name = name;
    this.color = color;
}
var apple = new Fruit("apple", "red");

// (apple != null)
apple instanceof Object  // true
apple instanceof Array   // false

<p><strong>3、使用 Object.prototype.toString.call()判斷</strong></p> <p>call()方法能夠改變this的指向,那麼把Object.prototype.toString()方法指向不一樣的數據類型上面,返回不一樣的結果</p>segmentfault

Object.prototype.toString.call(1)
"[object Number]"

Object.prototype.toString.call(NaN);
"[object Number]"

Object.prototype.toString.call("1");
"[object String]"

Object.prototype.toString.call(true)
"[object Boolean]"

Object.prototype.toString.call(null)
"[object Null]"

Object.prototype.toString.call(undefined)
"[object Undefined]"

Object.prototype.toString.call(function a() {});
"[object Function]"

Object.prototype.toString.call([]);
"[object Array]"

Object.prototype.toString.call({});
"[object Object]"

<p><strong>最後咱們能夠定義一個完美的判斷數據類型的方法 _typeof()</strong></p>數組

function _typeof(obj){
  var s = Object.prototype.toString.call(obj);
  return s.match(/\[object (.*?)\]/)[1].toLowerCase();
};


_typeof([12,3,343]);
"array"

_typeof({name: 'zxc', age: 18});
"object"

_typeof(1);
"number"

_typeof("1");
"string"

 _typeof(null);
"null"

_typeof(undefined);
"undefined"

_typeof(NaN);
"number"

_typeof(Date);
"function"

_typeof(new Date());
"date"

_typeof(new RegExp());
"regexp"

來源:http://www.javashuo.com/article/p-dszcxqxv-he.htmlapp

相關文章
相關標籤/搜索