日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

详解js中typeof、instanceof与constructor

發(fā)布時(shí)間:2025/4/16 编程问答 16 豆豆
生活随笔 收集整理的這篇文章主要介紹了 详解js中typeof、instanceof与constructor 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

typeof返回一個(gè)表達(dá)式的數(shù)據(jù)類型的字符串,返回結(jié)果為js基本的數(shù)據(jù)類型,包括number,boolean,string,object,undefined,function.語(yǔ)法為typeof(data) 或 typeof data

instanceof則為判斷一個(gè)對(duì)象是否為某一數(shù)據(jù)類型,或一個(gè)變量是否為一個(gè)對(duì)象的實(shí)例;返回boolean類型
語(yǔ)法為 o instanceof A

以下為綜合實(shí)例:


?1<script?type="text/javascript">
?2<!
?3alert("typeof(1):"?+?typeof(1));//number
?4alert("typeof(\"abc\"):"?+?typeof("abc"));//string
?5alert("typeof(true):"?+typeof(true));//boolean
?6alert("typeof(2009-2-4):"?+?typeof(2009-2-4));//number
?7alert("typeof(\"2009-2-4\"):"?+?typeof("2009-2-4"));//string
?8alert("typeof(m):"?+?typeof(m));//undefined
?9var?d=new?Date();
10alert("typeof(d):"?+?typeof(d));//object
11function?Person(){};
12alert("typeof(Person):"?+?typeof(Person));//function
13var?a=new?Array();
14alert("typeof(a):"?+?typeof(a));//object
15alert("a?instanceof?Array:"?+?(a?instanceof?Array));
16var?h=new?Person();
17var?o={};
18alert("h?instanceof?Person:"?+?(h?instanceof?Person));//true
19alert("h?instanceof?Object:"?+?(h?instanceof?Object));//true
20alert("o?instanceof?Object:"?+?(o?instanceof?Object));//true
21alert(typeof(h));//object
22//–>
23</script>

js中constructor較少使用,如果不是搜索到相關(guān)construtor相關(guān)的資料,我之前從沒(méi)有注意到j(luò)s還有這個(gè)函數(shù)。

使用typeof的一個(gè)不好的地方就是它會(huì)把Array還有用戶自定義函數(shù)都返回為object

1<script?type="text/javascript">
2<!
3var?j=2;
4alert(typeof(j));//number
5alert("j.constructor:"?+?j.constructor);//function?…
6alert(typeof(j.constructor));//function
7//–>
8</script>


可以看到j(luò)s.constructor返回的是一些字符串,大家都應(yīng)該能看到這是一個(gè)function類型,此例為Number()為Number對(duì)象的構(gòu)造函數(shù),Number()用于將其參數(shù)轉(zhuǎn)換為數(shù)字number類型,并返回轉(zhuǎn)換結(jié)果(若不能轉(zhuǎn)換則返回 NaN)。

因此在以后的js判斷數(shù)據(jù)類型時(shí)可以使用以下方式來(lái)得到其詳細(xì)數(shù)據(jù)類型

1if((typeof o=="object") && (o.constructor==Number)){
2
3}

這里還要注意,constructor只能對(duì)已有變量進(jìn)行判斷,而typeof則可對(duì)未聲明變量進(jìn)行判斷(返回undefined)。

總結(jié)

以上是生活随笔為你收集整理的详解js中typeof、instanceof与constructor的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。