【前端js】一分鐘掌握undefined,not defined,null和NaN的區別


一、undefined,not defined,和null的不同點:

1.含義不同:

1.1 not defined
是一個報錯,表示一個變量沒有聲明也沒有定義(not declared at a given point of time )

console.log(b)//Uncaught ReferenceError: b is not defined
window.b = 5;

1.2 undefined
不是一個報錯undefined是一種基礎數據類型,也是掛載在window對象的一個屬性,不是關鍵字。從js解析器的層面上解釋,實際上是js解析到這個變量時,發現作用域裏面沒有這個變量.

window.undefined//undefinde

情形一:當你引用了一個變量,變量被聲明瞭,但沒有初始化時,(we declare a variable without assigning any value to it),這個變量的值就是 undefined

let name;
console.log(name); //undefined

情形二: 引用了對象/數組未聲明的屬性/方法,

//Object
let obj = {a:3};
console.log(obj.b);//undefined
//Array
let arr = [1];
console.log(arr[1]);//undefined

舉個?——常見的一種undeifined報錯,使用一個數組的的方法時報錯method is undefined,其實是說明這個變量指向的不是一個數組(比如null/undefined),這些類型自然沒有數組的原型方法,
正確姿勢:因此要使用一個數組的方法時,需要先判斷這個數組不爲null,避免報錯

let arr2;
console.log(arr2.length)// Uncaught TypeError: Cannot read property 'length' of undefined
//正確姿勢
arr2 && console.log(arr2.length)

1.3 null
null表示一個變量已聲明定義了一個空值,表示一個空對象,是一個關鍵字

Object(null)//{}

1.4 NaN
NaN是一種數字類型,常用作數字運算返回的結果中,表示結果無法轉化成數字的數字類型,它不等於自身

console.log(s="a"*1)//NaN

2.typeof運算符區別他們

undefined返回undefined;null返回object對象,NaN返回number。

typeof undefined//"undefined"
typeof null//"object"
typeof NaN//"number"

3.轉化成數字不同:

undefined和NaN返回NaN;null返回0。

Number(undefined)//NaN
Number(NaN)//NaN
Number(null)//0

4.是否有方法和屬性

undefined和null都沒有方法,但是NaN有方法,比如下面的原始值方法

undefined.valueOf() 
//Uncaught TypeError: Cannot read property 'valueOf' of undefined
null.valueOf() 
// //Uncaught TypeError: Cannot read property 'valueOf' of null
NaN.valueOf()//NaN

5.相等判斷

//全等判斷===
console.log(NaN===NaN)//false
console.log(undefined===undefined)//true
console.log(null===null)//true
//相等判斷==,操作符會先轉換操作數(通常稱爲強制轉型),然後再比較它們的相等性。
console.log(NaN==NaN)//false
console.log(undefined==null)//true
console.log(NaN==null)//true
console.log(NaN==undefined)//false

二、相同點:

1.都是“假值”,

布爾值會轉成false

Boolean(undefined)//false
Boolean(null)//false
Boolean(NaN)//false

三、開發中的使用:

1.創建一個對象/變量時候,可以先賦值爲null

var a =null

2.函數需要傳多個參數時候,判斷函數的某個參數是否傳了

if(x===undefined)

3.判斷某個值是否爲空,兩個等號是因爲會直接對值隱式轉化。

x==null
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章