为什么null在JavaScript中被认为是一个对象?
正在检查
if ( object == null )
Do something
和
if ( !object )
Do something
?
还有:
null和undefined之间的区别是什么?
为什么null在JavaScript中被认为是一个对象?
正在检查
if ( object == null )
Do something
和
if ( !object )
Do something
?
还有:
null和undefined之间的区别是什么?
当前回答
Null是一个对象。它的类型是null。Undefined不是一个对象;其类型是未定义的。
其他回答
JavaScript中许多不同的null检查的比较:
http://jsfiddle.net/aaronhoffman/DdRHB/5/
// Variables to test
var myNull = null;
var myObject = {};
var myStringEmpty = "";
var myStringWhiteSpace = " ";
var myStringHello = "hello";
var myIntZero = 0;
var myIntOne = 1;
var myBoolTrue = true;
var myBoolFalse = false;
var myUndefined;
...trim...
http://aaron-hoffman.blogspot.com/2013/04/javascript-null-checking-undefined-and.html
一些精度:
Null和undefined是两个不同的值。一个表示没有名称的值,另一个表示没有名称。
对于if(o), if中发生的事情如下所示:
括号o中的表达式被求值,然后if语句开始对括号中的表达式的值进行类型强制——在我们的例子中是o。
JavaScript中的Falsy(将被强制为false)值为:",null, undefined, 0和false。
typeof null; // object
typeof undefined; // undefined
null值表示有意不存在任何对象值。它是JavaScript的基本值之一,在布尔操作中被视为假值。
var x = null;
var y;
X被声明并定义为null
Y声明了,但没有定义。它声明时没有值,所以没有定义。
Z没有被声明,所以如果你试图使用Z,它也是未定义的。
Null不是一个对象,它是一个基本值。例如,不能向其添加属性。有时人们错误地认为它是一个对象,因为typeof null返回“object”。但这实际上是一个错误(甚至可能在ECMAScript 6中被修复)。
null和undefined的区别如下:
undefined: used by JavaScript and means “no value”. Uninitialized variables, missing parameters and unknown variables have that value. > var noValueYet; > console.log(noValueYet); undefined > function foo(x) { console.log(x) } > foo() undefined > var obj = {}; > console.log(obj.unknownProperty) undefined Accessing unknown variables, however, produces an exception: > unknownVariable ReferenceError: unknownVariable is not defined null: used by programmers to indicate “no value”, e.g. as a parameter to a function.
检查变量:
console.log(typeof unknownVariable === "undefined"); // true
var foo;
console.log(typeof foo === "undefined"); // true
console.log(foo === undefined); // true
var bar = null;
console.log(bar === null); // true
作为一般规则,在JavaScript中应该总是使用===,而永远不要使用==(==执行各种可能产生意外结果的转换)。检查x == null是一个边缘情况,因为它适用于null和undefined:
> null == null
true
> undefined == null
true
检查变量是否有值的一种常见方法是将其转换为布尔值,然后看它是否为真。该转换由if语句和布尔运算符!(“不”)。
function foo(param) {
if (param) {
// ...
}
}
function foo(param) {
if (! param) param = "abc";
}
function foo(param) {
// || returns first operand that can't be converted to false
param = param || "abc";
}
这种方法的缺点:以下所有值的计算结果都是false,所以你必须小心(例如,上面的检查不能区分undefined和0)。
定义,零 布尔值:假 数字:+0,-0,NaN 弦:“”
你可以通过使用boolean作为函数来测试到boolean的转换(通常它是一个构造函数,用于new):
> Boolean(null)
false
> Boolean("")
false
> Boolean(3-3)
false
> Boolean({})
true
> Boolean([])
true
null和undefined的主要区别在于null表示 一个缺失的对象,而undefined表示变量的未初始化状态。
你可以认为null是一个未定义的对象,但未定义只是未定义的 因为它的类型没有定义。
let a;
console.log(a); //undefined, since it is declared but not initialized
console.log(null == undefined) //true
console.log(null === undefined) // false
console.log(typeof null) //object
console.log(typeof undefined) //undefined