js-資料類型

來源:互聯網
上載者:User

標籤:

最近在看視頻學習,把相關的知識記錄,匯總一下,

js的未經處理資料類型包含五種:number、string、boolean、null、undefined

還有一個大家常見到的也就是object(Date、Function、Array等)

如何判斷類型,主要有以下幾種:typeof、instanceof、Object.prototype.toString、constructor、duck type

1)typeof:適合判斷函數和基本類型的判斷,例如:

  typeof 1-》‘number’,

  typeof true-》‘boolean’,

  typeof function-》‘function’,

  typeof undefined-》‘undefined’,

  typeof new Object()-》‘object’,

  typeof [1,2]-》‘object’,

  typeof NaN-》‘number’,

  typeof null-》‘object’(曆史遺留問題)

發現沒有,對基本類型比較合適,遇到數組,還是object,無法精確區分object,這時候引入instanceof(基於原型鏈prototype)

2)instanceof:obj instanceof Object 適合判斷物件類型(基於原型鏈prototype)

舉個例子:

var child = function (){};
var parent = function (){};
child.prototype = new parent();
var c = new child();
var p = new parent();
document.write(c instanceof parent);//true

有關prototype,可以查詢相關的文檔,以後我也會在部落格中總結一下前人總結的特點

簡單說一下這個例子,每一個執行個體對象(c,p)都有一個_proto_屬性(原型屬性),他們會指向自己對象(child,parent)的prototype

第一步,會判斷c的_proto_指向的child的prototype是否等於parent的prototype,不等於,

第二步,繼續找c的上一級的原型,前面定義了child.prototype = new parent();也就是說c的_proto_的_proto_跟parent的prototype是一樣的,這裡就返回true了

3)Object.prototype.toString:適合內建對象和基本元素,注意ie的相容(ie6,7,8 返回[object Object])

例如:

Object.prototype.toString.apply([])===‘[object Array]‘;

Object.prototype.toString.apply(function(){})===‘[object Function]‘;

Object.prototype.toString.apply(null)===‘[object Null]‘;

Object.prototype.toString.apply(undefined)===‘[object Undefined]‘;

這裡簡單查一下jq的類型判斷的部分源碼:

type: function( obj ) { return obj == null ? String( obj ) : class2type[ toString.call(obj) ] || "object";},
isFunction: function( obj ) {
 return jQuery.type(obj) === "function";},
isArray: Array.isArray || function( obj ) { return jQuery.type(obj) === "array";},
jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) {
 class2type[ "[object " + name + "]" ] = name.toLowerCase(); });

這裡我想說的就是jq的設計技巧,很巧妙的把我們用到的類型,用數組同統一封裝一下,js的很多原生的方法在jq也定義了一下。這裡借鑒一下這個思路

js-資料類型

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.