麻豆小视频在线观看_中文黄色一级片_久久久成人精品_成片免费观看视频大全_午夜精品久久久久久久99热浪潮_成人一区二区三区四区

首頁 > 學院 > 開發設計 > 正文

JS中typeof與instanceof的區別

2019-11-14 11:57:05
字體:
來源:轉載
供稿:網友

javaScript 中 typeof 和 instanceof 常用來判斷一個變量是否為空,或者是什么類型的。但它們之間還是有區別的:typeoftypeof 是一個一元運算,放在一個運算數之前,運算數可以是任意類型。它返回值是一個字符串,該字符串說明運算數的類型。typeof 一般只能返回如下幾個結果:number,boolean,string,function,object,undefined。我們可以使用 typeof 來獲取一個變量是否存在,如 if(typeof a!="undefined"){alert("ok")},而不要去使用 if(a) 因為如果 a 不存在(未聲明)則會出錯,對于 Array,Null 等特殊對象使用 typeof 一律返回 object,這正是 typeof 的局限性。

網上的一個小例子:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><script language="Javascript" type="text/javascript">document.write ("typeof(1): "+typeof(1)+"<br>");document.write ("typeof(NaN): "+typeof(NaN)+"<br>");document.write ("typeof(Number.MIN_VALUE): "+typeof(Number.MIN_VALUE)+"<br>");document.write ("typeof(Infinity): "+typeof(Infinity)+"<br>");document.write ("typeof(/"123/"): "+typeof("123")+"<br>");document.write ("typeof(true): "+typeof(true)+"<br>");document.write ("typeof(window): "+typeof(window)+"<br>");document.write ("typeof(Array()): "+typeof(new Array())+"<br>");document.write ("typeof(function(){}): "+typeof(function(){})+"<br>");document.write ("typeof(document): "+typeof(document)+"<br>");document.write ("typeof(null): "+typeof(null)+"<br>");document.write ("typeof(eval): "+typeof(eval)+"<br>");document.write ("typeof(Date): "+typeof(Date)+"<br>");document.write ("typeof(sss): "+typeof(sss)+"<br>");document.write ("typeof(undefined): "+typeof(undefined)+"<br>")</script><title>javascript類型測試</title></head><body></body></html>instanceofinstance:實例,例子a instanceof b?alert("true"):alert("false"); //a是b的實例?真:假instanceof 用于判斷一個變量是否某個對象的實例,如 var a=new Array();alert(a instanceof Array); 會返回 true,同時 alert(a instanceof Object) 也會返回 true;這是因為 Array 是 object 的子類。再如:function test(){};var a=new test();alert(a instanceof test) 會返回談到 instanceof 我們要多插入一個問題,就是 function 的 arguments,我們大家也許都認為 arguments 是一個 Array,但如果使用 instaceof 去測試會發現 arguments 不是一個 Array 對象,盡管看起來很像。另外:測試 var a=new Array();if (a instanceof Object) alert('Y');else alert('N');得'Y’但 if (window instanceof Object) alert('Y');else alert('N');得'N'。(PS:經證實,目前主流瀏覽器都返回Y。)所以,這里的 instanceof 測試的 object 是指 js 語法中的 object,不是指 dom 模型對象。使用 typeof 會有些區別alert(typeof(window)) 會得 object


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 91精品国产乱码久久久久久久久 | 午夜精品福利影院 | 日本在线不卡一区二区三区 | 亚洲欧美在线看 | 日韩在线播放第一页 | 99热久草 | 久草在线手机视频 | 久草免费新视频 | videos 欧美| 九九热免费视频在线观看 | 国产一国产精品一级毛片 | 日本精品久久久久 | 91精品国产日韩91久久久久久360 | 久久艹逼| 成人午夜亚洲 | 91午夜少妇三级全黄 | 西川av在线一区二区三区 | 欧美人xx| 成人国产精品一区二区毛片在线 | 91美女视频在线 | 精品一区在线视频 | 精品久久久久久久久久久久包黑料 | 国产精品爆操 | 成人午夜免费观看 | 国产一级aaa全黄毛片 | 久草导航 | 久久免费视屏 | 免费在线观看午夜视频 | 日韩激情一区 | 成人444kkkk在线观看 | 国产乱一区二区三区视频 | 鲁丝片一区二区三区免费入口 | 狼人狠狠干 | 黄色大片大毛片 | 99视频网址 | 天天撸日日夜夜 | av免费在线不卡 | 黄色大片在线免费观看 | 欧美性色生活片免费播放 | 久久国产精 | 国产精品成人av片免费看最爱 |