JS typeof 與 instanceof

JS中經常使用來斷定變量類型的兩個函數爲 typeof 和 instanceofphp

typeof 的結果有 

undefined, number, boolean, string, function, 
object[
null, 
Array,
String,
Date.....]

要注意的地方是 typeof null的結果爲object, null在js中是一種特殊的對象,而非等同於 undefinedsql

null 和 undefined 並非等價的函數

var tmp = null; // 雖然tmp是null,但我也定義了
var undef; //聲明但沒定義
alert(typeof tmp); // object
alert(typeof undef); // undefined

因此判斷一個值是否是null的時候直接用 tmp == null便可,切勿使用typeof,null是一種特殊的對象spa

// 標量 //
typeof 123; // number
typeof 'string'; // string
typeof true; // boolean
// 函數 //
typeof function(){}; //function
// 對象 //
typeof new String('string'); // object
typeof null; //objecttype

而判斷一個變量是否被定義則可code

var temp;
typeof temp === "undefined"; //true 類型名
temp == undefined; //true 全部未定義的變量其實都是undefined

instanceof 能夠判斷非標量的類型

1 instanceof Number; //false
new Number(1) instanceof Number; //true
'string' instanceof String; // false
new String('string') instanceof String; // true
true instanceof Boolean; //false
new Boolean(true) instanceof Boolean; //true

注意 js 中分爲引用類型和對象實例,new 一個引用類型構造函數可返回此類型的一個實例,類型能夠本身建立,也能夠使用咱們平時經常使用的 Object Array Date 等,同事要注意標量並非但能夠轉換爲某類型的實例對象

相關文章
相關標籤/搜索