聊一聊JavaScript中typeof那點事兒

2021-09-16 12:53:49 字數 1818 閱讀 3083

js是一門指令碼化語言,它在宣告變數時不需確定變數的型別,js在執行時會自動判斷。那麼怎麼判斷變數的型別呢?js提供了typeof運算子,用來判斷變數是什麼型別。

方式一:

typeof(表示式)

(對表示式做運算)

方式二:

typeof 變數名

(對變數做運算) 型別

結果string

「string」

number

「number」

boolean

「boolean」

undefined

「undefined」

object

「object」

function函式物件

「function」

1 . string

字元型別的值或變數

alert

(typeof

('a'))

;// string

alert

(typeof(""

));// string

2 . number

數字型別的值或變數

alert

(typeof(0

));//number

alert

(typeof

(121))

;//number

alert

(typeof

(nan))

;//number

alert

(typeof

(math.

ln2));

//number

alert

(typeof

(infinity))

;//number

3 . boolean

布林型別的值或變數

alert

(typeof

(flase));

//boolean

alert

(typeof

(true))

;//boolean

4 . undefined

未定義的值或變數

//變數未宣告時

alert

(typeof

(a))

;//undefined

//變數值就是undefined

var a = undefined;

alert

(typeof

(a))

;//undefined

5 . object

物件型別的值,變數或null

var a =

;//物件

alert

(typeof

(a))

;//object

var b =

[1,2,3];

//陣列

alert

(typeof

(b))

;//object

alert

(typeof

(null);

//object 這是個特例將null作為object型別處理

6 . function

函式型別的值或變數

alert

(typeof

(function()

);//函式方法

alert

(typeof

(math.sin)

);

聊一聊小甜餅

cookies程式設計 cookie是儲存在客戶端的小文字,儲存的位置分為兩種 cookie可能儲存在客戶端瀏覽器的所佔記憶體中,關閉瀏覽器後,cookies就不再存在。cookie也可能儲存在客戶pc機的硬碟上,設定有效時間,超過有效時間後失效。cookie的常見應用 簡化登入 很多 在登入時,可...

聊一聊動態規劃

一 問題 看乙個經常被引用的問題 例子1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 例子2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 問你例子1是多少時,你乙個個算後,結果是20 接著問你例子2時,你會馬上說出21,為什...

聊一聊元資料

這個話題來自我的msn space。這是原文 元資料 metadata 這個詞現在到處氾濫。其實我對元資料充其量只能說有自己的理解而已,並不能確信這個理解是正確的。我認為,資料結構分為三個層次 uml可是四層哦 例項層 直接描述特異化的資料場景 元資料層 描述例項的結構的一組資料 元資料的元資料層 ...