Javascript類(lèi)型檢測(cè)-創(chuàng)新互聯(lián)

1.typeof

typeof 適合基本類(lèi)型及function檢測(cè),遇到null失效。

創(chuàng)新互聯(lián)從2013年成立,先為德州等服務(wù)建站,德州等地企業(yè),進(jìn)行企業(yè)商務(wù)咨詢(xún)服務(wù)。為德州企業(yè)網(wǎng)站制作PC+手機(jī)+微官網(wǎng)三網(wǎng)同步一站式服務(wù)解決您的所有建站問(wèn)題。
typeof 100; // "number"
typeof true; // "boolean"
typeof fun(); // "function"
typeof NaN; // "number"
typeof undefined; // "undefined"
typeof null; // "object"
typeof new Object(); // "object"
typeof [1,2]; // "object"
2.instanceof

instanceof一般用于對(duì)象類(lèi)型的判斷,是基于原型鏈的判斷。

//obj instanceof Object
[1,2] instanceof Array === true
new Object() instanceof Array === false

function Student(){}
function Teacher(){}

var s = new Student()

console.log(s instanceof Student) // true
console.log(s instanceof Teacher) // false

Student.prototype = new Teacher()
var s2 = new Student()
console.log(s2 instanceof Student) // true
console.log(s2 instanceof Teacher) // true

PS:適合自定義對(duì)象,也可以用來(lái)檢測(cè)原生對(duì)象。不同window或iframe間的對(duì)象類(lèi)型檢測(cè)不能用instanceof。

3.Object.prototype.toString.apply()

通過(guò){}.toString拿到,適合內(nèi)置對(duì)象和基本類(lèi)型,遇到null和undefined失效(IE678返回[object Object])。

Object.prototype.toString.apply([]) === "[object Array]"
Object.prototype.toString.apply(function(){}) === "[object Function]"
Object.prototype.toString.apply(null) === "[object Null]" // IE6/7/8返回"[object Object]"
Object.prototype.toString.apply(undefined) === "[object Undefined]"
Object.prototype.toString.apply(123) === "[object Number]"
 Object.prototype.toString.apply('123') === "[object String]"
 Object.prototype.toString.apply(true) === "[object Boolean]"

 console.log(Object.prototype.toString.apply(new Object())) //[object Object]
function Student(){}
var s = new Student()
console.log(Object.prototype.toString.apply(s)) //[object Object]

console.log(Object.prototype.toString.apply(window)) // [object Window]
console.log(Object.prototype.toString.apply(new Date())) //[object Date]

另外有需要云服務(wù)器可以了解下創(chuàng)新互聯(lián)scvps.cn,海內(nèi)外云服務(wù)器15元起步,三天無(wú)理由+7*72小時(shí)售后在線,公司持有idc許可證,提供“云服務(wù)器、裸金屬服務(wù)器、高防服務(wù)器、香港服務(wù)器、美國(guó)服務(wù)器、虛擬主機(jī)、免備案服務(wù)器”等云主機(jī)租用服務(wù)以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡(jiǎn)單易用、服務(wù)可用性高、性?xún)r(jià)比高”等特點(diǎn)與優(yōu)勢(shì),專(zhuān)為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應(yīng)用場(chǎng)景需求。

文章題目:Javascript類(lèi)型檢測(cè)-創(chuàng)新互聯(lián)
文章起源:http://www.bm7419.com/article14/cdjpde.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供搜索引擎優(yōu)化、網(wǎng)站建設(shè)商城網(wǎng)站、網(wǎng)站內(nèi)鏈、關(guān)鍵詞優(yōu)化、網(wǎng)站收錄

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)

成都做網(wǎng)站