多多色-多人伦交性欧美在线观看-多人伦精品一区二区三区视频-多色视频-免费黄色视屏网站-免费黄色在线

國內最全IT社區平臺 聯系我們 | 收藏本站
阿里云優惠2
您當前位置:首頁 > web前端 > jscript > Object.prototype.toString.call() 區分對象類型

Object.prototype.toString.call() 區分對象類型

來源:程序員人生   發布時間:2014-02-05 07:27:44 閱讀次數:2860次

在 JavaScript 里使用 typeof 來判斷數據類型,只能區分基本類型,即 “number”,”string”,”undefined”,”boolean”,”object” 五種。對于數組、函數、對象來說,其關系錯綜復雜,使用 typeof 都會統一返回 “object” 字符串。

要想區別對象、數組、函數單純使用 typeof 是不行的。或者你會想到 instanceof 方法,例如下面這樣:

var a = {};var b = [];var c = function () {};//a b c 都是 Object 的實例console.log(a instanceof Object) //trueconsole.log(b instanceof Object) //trueconsole.log(c instanceof Object) //true//只有 Array 類型的 b 才是 Array 的實例console.log(a instanceof Array) //falseconsole.log(b instanceof Array) //trueconsole.log(c instanceof Array) //false//只有 Function 類型的 c 才是 Function 的實例console.log(a instanceof Function) //falseconsole.log(b instanceof Function) //falseconsole.log(c instanceof Function) //true

從以上代碼來看,要判斷復合數據類型,可以如下判斷:

//對象(a instanceof Object) && !(a instanceof Function) && !(a instanceof Function)//數組(a instanceof Object) && (a instanceof Array)//函數(a instanceof Object) && (a instanceof Function)

更簡便的方式,即是使用 Object.prototype.toString.call() 來確定類型,ECMA 5.1 中關于該方法的描述[1]是這樣的:

When the toString method is called, the following steps are taken:
If the this value is undefined, return “[object Undefined]“.
If the this value is null, return “[object Null]“.
Let O be the result of calling ToObject passing the this value as the argument.
Let class be the value of the [[Class]] internal property of O.
Return the String value that is the result of concatenating the three Strings “[object ", class, and "]“.

由于 JavaScript 中一切都是對象,任何都不例外,對所有值類型應用 Object.prototype.toString.call() 方法結果如下:

console.log(Object.prototype.toString.call(123)) //[object Number]console.log(Object.prototype.toString.call('123')) //[object String]console.log(Object.prototype.toString.call(undefined)) //[object Undefined]console.log(Object.prototype.toString.call(true)) //[object Boolean]console.log(Object.prototype.toString.call({})) //[object Object]console.log(Object.prototype.toString.call([])) //[object Array]console.log(Object.prototype.toString.call(function(){})) //[object Function]

所有類型都會得到不同的字符串,幾乎完美。

[1] Object.prototype.toString ()

生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈
程序員人生
------分隔線----------------------------
分享到:
------分隔線----------------------------
關閉
程序員人生
主站蜘蛛池模板: 五月天看片 | 在线中文字幕观看 | 叼嘿免费视频 | 亚洲综合国产一区二区三区 | 亚洲欧美色欧另类欧 | 性高湖久久久久久久久aaaaa | 在线免费亚洲 | 日本a一级毛片免费观看 | 欧美专区一区 | 中文字幕在线观看网站 | 亚州春色校园另类 | 国产视频一区二 | 国产精品国产精品国产专区不卡 | 最近中文字幕更新免费 | 日韩欧美一级a毛片欧美一级 | 波多野结衣中文字幕在线视频 | 乌克兰性欧美精品高清bd | 老年人一级特黄aa大片 | 国产a不卡片精品免费观看 国产a国产片色老头 | 欧洲亚洲综合一区二区三区 | 国产美女亚洲精品久久久久久 | 久久久精品一级二级三级 | 日韩在线a视频免费播放 | 免费播放成人生活片 | 日本高清另类videohd | 国产成人高清亚洲一区久久 | 欧美一区二区久久精品 | 国产福利片在线 易阳 | 亚洲色大成网站www 亚洲色大成网站www久久九九 | 欧美在线综合 | 亚洲日韩中文字幕天堂不卡 | 91精品免费在线观看 | 欧美一级毛级毛片 | 校园春色亚洲激情 | 色精品一区二区三区 | 欧美精品一区二区在线观看 | 伊人色影院 | 亚洲成年人在线观看 | 一级看片免费视频 | 国产成人久久精品推最新 | 在线播放一区二区三区 |