天天看點

javaScript中is-not-defined,undefined和null的差別is not defined與undefinedundefined 與 null

is not defined與undefined

之前沒太注意is not defined和undefined有什麼差別,每次都是簡單的把兩者了解為未定義,現在回過頭來梳理js基礎的時候才發現其中差別還是很鮮明的。

先從單純的字面意思來了解一下(有道詞典):

is not defined: 未定義

not defined: 未定義,沒有定義,無法定義

&&

undefined: 不明确的

單從字面意思大體也能看出兩者的差別:前者是沒有定義,也就是說沒有;後者是不明确的,也就是說不知道有沒有定義.

not defined

看demo1:

12 console.log(a) // 報錯:a is not defined 終止運作
一個未定義 的變量是沒有聲明的變量,這樣的變量在使用時會直接報錯誤。

undefined

一個定義了但未指派的 變量

demo2:

123 var aconsole.log(a) // 未報錯,提示: undefined

一個定義了但把值賦為undefined的 變量

demo3:

1234 var p = 1p = undefinedconsole.log(p) // 未報錯,提示: undefined

一個對象沒有指派的屬性

demo4:

12 console.log(window.a)// 未報錯,提示: undefined

demo5:

123 var a = []console.log(a.b)// 未報錯,提示: undefined

demo6:

123 var a = {}console.log(a.b)// 未報錯,提示: undefined

一個沒有傳回值的函數

demo7:

123 function f() {console.log(1)}console.log(f())// 未報錯,提示: undefined
有一點需要注意的是not defined 和 undefined 的typeof()的值都為”undefined”,是以無法用typeof()來判斷這兩者。

undefined 與 null

兩者相同–在if語句裡都被解析為false

demo8:

12 !undefined ? console.log('undefined is false') : console.log('undefined is not false')// undefined is false

demo9:

12 !null? console.log('null is false') : console.log('null is not false')// null is false

用法的不同

雖然null和undefined基本是同義的,但是在用法上還是有一些細微的差别的

null

null表示“沒有對象”,即此處不該有值

  1. 作為函數的參數,表示該函數的參數不是對象。
  2. 作為對象原型鍊的終點。

    demo10:1 2Object.getPrototypeof(object.prototype) // null

undefined

如上文demo2-demo7 部分