js中typeof判斷數據類型


js變量能夠保存多種數據類型數值、字符串值、布爾值、數組、對象等等;

eg:var length=7;

  var lastName="Gates";

  var x=true;

  var y=false;

  var cars=["NISSAN","白色","日產"];

       var x={firstName:"Bill",lastName:"Gates",age:"18"};

 

 

typeof運算符

您可使用js的typeof來確定js變量的類型

typeof運算符返回變量或表達式的類型:

typeof  0  //返回"number"

typeof  " "   //返回"string"

typeof  "Bill"  //返回"string"

typeof true   //返回"boolean"

typeof false  //返回"boolean"

typeof  x   //返回““undefined(假如x沒有值)”

 

特殊情況:

typeof 運算符對數組返回“object”,因為在js中數組屬於對象。

1、在js中,沒有值的變量,其值是undefined。typeof也返回undefined。

  eg:var car;

        typeof car;   //返回"undefined"

2.空值與undefined不一樣。

空的字符串既有值也有類型。

eg:var car=" ";

  typeof car;  //返回"string"

3.var person=null;  //返回object

 

typeof運算符把對象、數組或null返回object。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM