javascrit中undefined和null的區別
1、Undefined
Undefined 型別只有一個值,即特殊的undefined。根據工作中總結,只要有這幾種情況下會出現undefined。1.定義變數,但是沒有初始化時,如var a;
2.呼叫某個函式時,實參個數小於形參個數時,未實參化的形參在函式呼叫過程中的值是undefined;
3.呼叫某個物件還沒有新增的屬性時,也會返回undefined;
var obj={} console.log(obj.name);//undefined 複製程式碼
4.呼叫某個沒有返回值的函式,也會返回undefined;
function Person(name,age){ this.name=name; this.age=age; } var p=Person("李四",23);//此時的p=undefined; 複製程式碼
5.對未初始化的變數
執行 typeof 操作符會返回 undefined 值;
6.對未宣告的變數
執行 typeof 操作符同樣也會返回 undefined 值。
var message; // 這個變數宣告之後預設取得了 undefined 值 //未初始化的變數 alert(typeof message);// "undefined" //未申明的變數 alert(typeof age);// "undefined" 複製程式碼
2、Null 型別
1、手動設定變數的值或者物件某一個屬性值為null(在初始化物件時,手動設定物件為null。在作用域中不再需要使用某個物件時,把null賦值給那個變數解除引用,以釋放記憶體)
2、在javascript的DOM元素獲取中,如果沒有獲取到指定的元素物件,結果一般是null。
var d=document.getElementById("d"); console.log(d);//當沒有id為"d"的標籤時返回null 複製程式碼
3、Object.prototype._proto_的值也是null。(每一個物件都有__proto__屬性,指向對應的建構函式的prototype屬性,但是因為Object是所有類的基類,其沒有對應的建構函式,所有Object.prototype._proto_值為空);
console.log("a".__proto__); //指向的是String的prototype屬性 //String {"", length: 0, constructor: ƒ, anchor: ƒ, big: ƒ, blink: ƒ, …} 複製程式碼
4、在正則捕獲的時候,如果沒有捕獲到結果,預設也是null。