我想知道JavaScript中null和undefined之间的区别。
当前回答
请仔细阅读以下内容。它应该可以消除您对JavaScript中null和undefined之间区别的所有疑虑。此外,您可以在答案末尾使用效用函数来获取更具体的变量类型。
在JavaScript中,我们可以有以下类型的变量:
未声明的变量已声明但未分配的变量未定义文字赋值的变量赋值为文本null的变量变量分配了除未定义或null以外的任何值
以下逐一解释了每种情况:
未声明的变量只能使用返回字符串“undefined”的typeof运算符进行检查不能用松散相等运算符(==undefined)检查,更不用说严格相等运算符(===undefineed),以及if语句和三元运算符(?:)-这些抛出引用错误已声明但未分配的变量typeof返回字符串“undefined”==检查null返回true==未定义的检查返回true==检查null返回false==未定义的检查返回trueif语句和三元运算符(?:)是否错误未定义文字赋值的变量这些变量与已声明但未分配的变量完全相同。赋值为文本null的变量typeof返回字符串“object”==检查null返回true==未定义的检查返回true==检查null返回true==检查未定义返回falseif语句和三元运算符(?:)是否错误变量分配了除未定义或null以外的任何值typeof返回以下字符串之一:“bigint”、“boolean”、“function”、“number”、“object”、“string”、“symbol”
以下提供了正确检查变量类型的算法:
获取变量的类型,如果它不是“object”,则返回它检查null,因为typeof null也返回“object”使用switch语句对Object.protype.toString.call(o)求值,以返回更精确的值。Object的toString方法为本机/主机对象返回类似“[Object ConstructorName]”的字符串。对于所有其他对象(用户定义的对象),它始终返回“[object object]”如果最后一部分是这种情况(变量的字符串化版本为“[objectObject]”),并且参数returnConstructorBoolean为真,则它将尝试通过对其进行字符串化并从中提取名称来获取构造函数的名称。如果无法访问构造函数,将照常返回“object”。如果字符串不包含其名称,则返回“匿名”
(支持ECMAScript 2020之前的所有类型)
function TypeOf(o, returnConstructorBoolean) {
const type = typeof o
if (type !== 'object') return type
if (o === null) return 'null'
const toString = Object.prototype.toString.call(o)
switch (toString) {
// Value types: 6
case '[object BigInt]': return 'bigint'
case '[object Boolean]': return 'boolean'
case '[object Date]': return 'date'
case '[object Number]': return 'number'
case '[object String]': return 'string'
case '[object Symbol]': return 'symbol'
// Error types: 7
case '[object Error]': return 'error'
case '[object EvalError]': return 'evalerror'
case '[object RangeError]': return 'rangeerror'
case '[object ReferenceError]': return 'referenceerror'
case '[object SyntaxError]': return 'syntaxerror'
case '[object TypeError]': return 'typeerror'
case '[object URIError]': return 'urierror'
// Indexed Collection and Helper types: 13
case '[object Array]': return 'array'
case '[object Int8Array]': return 'int8array'
case '[object Uint8Array]': return 'uint8array'
case '[object Uint8ClampedArray]': return 'uint8clampedarray'
case '[object Int16Array]': return 'int16array'
case '[object Uint16Array]': return 'uint16array'
case '[object Int32Array]': return 'int32array'
case '[object Uint32Array]': return 'uint32array'
case '[object Float32Array]': return 'float32array'
case '[object Float64Array]': return 'float64array'
case '[object ArrayBuffer]': return 'arraybuffer'
case '[object SharedArrayBuffer]': return 'sharedarraybuffer'
case '[object DataView]': return 'dataview'
// Keyed Collection types: 2
case '[object Map]': return 'map'
case '[object WeakMap]': return 'weakmap'
// Set types: 2
case '[object Set]': return 'set'
case '[object WeakSet]': return 'weakset'
// Operation types: 3
case '[object RegExp]': return 'regexp'
case '[object Proxy]': return 'proxy'
case '[object Promise]': return 'promise'
// Plain objects
case '[object Object]':
if (!returnConstructorBoolean)
return type
const _prototype = Object.getPrototypeOf(o)
if (!_prototype)
return type
const _constructor = _prototype.constructor
if (!_constructor)
return type
const matches = Function.prototype.toString.call(_constructor).match(/^function\s*([^\s(]+)/)
return matches ? matches[1] : 'anonymous'
default: return toString.split(' ')[1].slice(0, -1)
}
}
其他回答
null是一个特殊的关键字,表示缺少值。
将其视为一种价值,例如:
“foo”是字符串,true为布尔值,1234是数字,null未定义。
undefined属性表示尚未为变量分配包含null的值。喜欢
var foo;
定义的空变量为null,数据类型为undefined
它们都表示一个没有值的变量的值
以及null不表示没有值的字符串-空字符串-
Like
var a = '';
console.log(typeof a); // string
console.log(a == null); //false
console.log(a == undefined); // false
现在如果
var a;
console.log(a == null); //true
console.log(a == undefined); //true
BUT
var a;
console.log(a === null); //false
console.log(a === undefined); // true
所以每个人都有自己的使用方法
undefined使用它来比较变量数据类型
null使用它来清空变量的值
var a = 'javascript';
a = null ; // will change the type of variable "a" from string to object
未定义表示变量已声明但没有值:
var var1;
alert(var1); //undefined
alert(typeof var1); //undefined
Null是赋值:
var var2= null;
alert(var2); //null
alert(typeof var2); //object
只是为了添加我的观点-
在C++等编译语言的情况下,优化编译器会删除只声明且从不在任何地方使用的变量[或在IDE中标记警告]。这最终意味着变量不存在,因为它的内存从未分配。
在javascript解释器的情况下,[我猜]一个变量仅从被赋予值的那一点起被视为存在。在此之前,它的类型是“undefined”,并且没有为它分配内存。因此,它的名称是undefineed。
javascript中的null是一个表示地址的值,但该地址还没有指向任何内容[不存在的引用]。然而,这是一个价值。
根据Ryan Morr关于这一主题的详尽文章。。。
“通常,如果您需要为变量或属性分配非值,将其传递给函数,或从函数返回,null几乎总是最佳选项。简单地说,JavaScript使用未定义,程序员应该使用null。”
参见探索空和未定义的永恒深渊
null和undefined都用于表示缺少某个值。
var a = null;
a被初始化和定义。
typeof(a)
//object
null是JavaScript中的对象
Object.prototype.toString.call(a) // [object Object]
var b;
b未定义且未初始化
未定义的对象财产也是未定义的。例如,“x”未在对象c上定义,如果您尝试访问c.x,它将返回undefined。
通常,我们为未定义的变量赋值null。