typeof 是運算子,注意不是函數,是運算子,其作用,是考察變數究竟是什麼類型。或曰,是變數是否定義或是否初始化的照妖鏡。傳回值是字串。
undefined 表示一個對象沒有被定義或者沒有被初始化。
null 表示一個尚未存在的對象的預留位置。
測試一,變數沒有定義的時候,只能使用 typeof
<input type="button" id="btnTest" onclick="Test()" value="測試" /> <script type="text/javascript"> function Test() { alert(i == null); //報錯 alert(i == undefined); //報錯 alert(typeof i == "undefined"); //true } </script>
測試二,變數有定義,但未初始化,typeof,undefined,null都可以使用
<script type="text/javascript"> function Test() { var i; alert(i == null); //true alert(i == undefined); //true alert(typeof i == "undefined"); //true i = 0; alert(i == null); //false alert(i == undefined); //false alert(typeof i == "undefined"); //false } </script>
測試三,函數參數跟變數類似
1、沒有參數
<input type="button" id="btnTest" onclick="Test()" value="測試" /> <script type="text/javascript"> function Test(i) { alert(i == null); //true alert(i == undefined); //true alert(typeof i == "undefined"); //true } </script>
2、有參數
<input type="button" id="btnTest" onclick="Test(0)" value="測試" /> <script type="text/javascript"> function Test(i) { alert(i == null); //false alert(i == undefined); //false alert(typeof i == "undefined"); //false } </script>
參考文章:點擊開啟連結