JavaScript 中有多少個表示“無”的值?
JavaScript 有兩個表示“無”的值,即 null 和 undefined。這兩個也是 JavaScript 中的原始資料型別。
Undefined
在這兩個值中,JavaScript 中的 Undefined 指的是,如果聲明瞭一個變數但沒有為其賦值,則該變數被稱為 undefined。物件也可以為 null。當物件沒有值時,它被稱為 null。
示例 1
這是 JavaScript 中 undefined 值的示例。
var str console.log('The value of given variable is:',str)
在上面的示例 1 中,聲明瞭一個名為“str”的變數。因此,由於它只是聲明瞭,沒有賦值,預設情況下它取值為“undefined”。當列印 undefined 變數的值時,它只顯示為“undefined”。
示例 2
以下是此值的另一個示例
var myVar if(myVar === void 0) { console.log("myVar has the value:",typeof(myVar)); }
示例 3
let a; console.log(a); function b() {} console.log(b())
NULL
JavaScript 中的 Null 型別為“Object”。其名稱本身就指明變數的值為空,或者可以說變數的值不存在(或為零)。與 undefined 不同,JavaScript 無法將值“null”賦給任何變數或物件。程式設計師或使用者必須將變數或物件賦值為 null。
示例 1
此示例演示了 JavaScript 中的“null”值:
var a = null; console.log("This value of given variable is:",a) console.log("The type of null value is:",typeof null)
在上面的示例中,變數直接賦值為 null。當列印該值時,它顯示為“null”。並且它還顯示 null 的型別為“Object”。
由於 null 表示零,因此當變數為 null 時可以執行算術運算並返回結果。但是,如果變數未定義,則無法執行算術運算,並返回 NaN(非數字)。
示例 2
此示例顯示可以對“undefined”和“null”值執行的操作:
var a console.log("The variable is:",a,"Type of is:",typeof a) console.log("Value of undefined when addition is done:",a+1) var b = null console.log("The variable is:",b,"Type of is:",typeof b) console.log("Value of null when addition is done:",b+1)
示例 3
let a = null; function b() { return null } console.log(a); console.log(b())
廣告