JavaScript 中有多少个空值?
javascriptobject oriented programmingprogramming
JavaScript 中有两个空值,即 null 和 undefined。这两个也是 JavaScript 中的原始类型。
Undefined
在这两个值中,JavaScript 中的 Undefined 表示如果声明了一个变量,但没有为该变量分配任何值,则该变量被称为未定义。对象也可以为空。当它没有值时,它被称为空。
示例 1
这是 JavaScript 中未定义值的示例。
var str console.log('The value of given variable is:',str)
在上面的示例 1 中,声明了一个名为"str"的变量。因此,由于它只是声明,没有分配任何值,默认情况下它将值设为"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
此示例显示了可以对"未定义"和"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())