你真的了解undefined嗎?

undefined既是一個基本數據類型也是一個原始值數據

  • 系統會給一個未賦值的變量賦值為undefined,返回的類型也是undefined
var a;
console.log(a); // 值undefined
console.log(typeof a);  // 類型undefined
  • 調用一個有參數的函數但是不傳參,這個參數也是undefined
function test(a){
    console.log(a); // 值undefined
    console.log(typeof a); //  類型undefined
    return a // // 值undefined
}
console.log(test());
  • 函數內部沒有顯式return東西時,系統默認返回undefined
function test(){
    var a = 9
}
console.log(test()); // undefined

undefined還是全局window上的一個屬性

window.undefined.png
  • 這個屬性是只讀的,不可配置,不可枚舉
console.log(window.undefined); // undefined
            
window.undefined = '123'
console.log(window.undefined);
            
for (let k in window) {
  if(k === undefined){
    console.log("訪問到了");
   }
 }



undefined.png
  • 不可重新定義
Object.defineProperty(window, "undefined", {
    enumerable: true,
    writable: true,
    configurable: true
})
//直接報錯
 Uncaught TypeError: Cannot redefine property: undefined
    at Function.defineProperty (<anonymous>)
    at test.html:9

undefined可以做變量名嗎??

  • 全局作用域下
var undefined = 1
console.log(undefined); // undefined
console.log(window.undefined); // undefined
  • 局部作用域下
function test(){
    var undefined = 1
    console.log(undefined); // 1
}
test()

undefined在局部作用域可以作為變量,undefined不是關鍵字也不是保留字,上面也說了在全局下,undefined是只讀的,所以在局部作用域中就可以使用,嚴格模式下仍然可以。但是開發中還是避免使用它做變量名

判斷類型

如果要判斷某個變量是否是undefined,必須使用“===”而不能使用“==”

var a;
if(a === undefined){
  console.log("執行了"); // 可以執行
  }

var b;
if(a == undefined){
  console.log("執行了"); // 可以執行
  }

為的就是與null進行區分,當a = null時,a == undefined返回的結果就是true

var a = null;
if(a == undefined){
  console.log("執行了");
}
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • JavaScript 用法 HTML 中的腳本必須位于 與 標簽之間。腳本可被放置在 HTML 頁面的 ...
    蜂子fightting閱讀 853評論 0 0
  • 函數和對象 1、函數 1.1 函數概述 函數對于任何一門語言來說都是核心的概念。通過函數可以封裝任意多條語句,而且...
    道無虛閱讀 4,630評論 0 5
  • JavaScript,通常縮寫為 JS,是一種解釋執行的編程語言。它是現在最流行的腳本語言之一。 JavaScri...
    神齊閱讀 4,963評論 1 32
  • let和const let和const作為es6新增的關鍵字,和var類似用來聲明變量。 區別: var定義變量,...
    不成KickFlip不改名閱讀 314評論 0 0
  • JavaScript簡介 JavaScript(簡稱“JS”) 是一種具有函數優先的輕量級,解釋型或即時編譯型的編...
    Joel_zh閱讀 214評論 0 0