JavaScript 中 typeof 和 instanceof 經常使用來判斷一個變量是否爲空,或者是什麼類型的。但它們之間仍是有區別的:javascript
typeof 是一個一元運算,放在一個運算數以前,運算數能夠是任意類型。html
它返回值是一個字符串,該字符串說明運算數的類型。typeof 通常只能返回以下幾個結果: number,boolean,string,function,object,undefined。咱們能夠使用 typeof 來獲取一個變量是否存在,如 if(typeof a!="undefined"){alert("ok")},而不要去使用 if(a) 由於若是 a 不存在(未聲明)則會出錯,對於 Array,Null 等特殊對象使用 typeof 一概返回 object,這正是 typeof 的侷限性。java
網上的一個小例子:dom
<!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>
instance:實例,例子測試
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 對象,儘管看起來很像。ui
另外:code
測試xml
var a=new Array();if (a instanceof Object) alert('Y');else alert('N');
得'Y’htm
但對象
if (window instanceof Object) alert('Y');else alert('N');
得'N'
因此,這裏的 instanceof 測試的 object 是指 js 語法中的 object,不是指 dom 模型對象。
使用 typeof 會有些區別
alert(typeof(window))
會得 object