空数组是否严格等于 JavaScript 中的任何内容? [英] Is an empty array strictly equal to anything in JavaScript?
问题描述
我对不同的数组值做了一系列测试:
I did a series of tests for different array values:
测试:
x === 0
x === ''
x === false
x === undefined
x === NaN
x === null
x === []
x === {}
x == 0
x == ''
x == false
x == undefined
x == NaN
x == null
x == []
x == {}
结果:
如果 x 是:
[NaN]
[false]
它没有通过所有测试.
如果 x 是:
[null]
[]
[[]]
[[[yep, no matter how deep]]]
[undefined]
['']
它通过了:
x==0
x==''
x==false
如果 x 是:
[0]
[{}]
通过了
x==0
x==false
我错过了什么吗?是否有一个空数组 []
严格等于 (===
)?
Am I missing something? Is there something an empty array []
strictly equal to (===
)?
此外,对于这些值:[NaN],[false], [null], [], [[]], [undefined], [''], [0], [{}]
,只有[].length
等于0
Also, for these values: [NaN],[false], [null], [], [[]], [undefined], [''], [0], [{}]
, only [].length
is equal to 0
关于如何检查数组是否为空 []
的最佳实践是什么?如果存在相互竞争的最佳实践,在哪些情况下最好使用它们?
What are the best practices on how to check if an array is empty []
? If there are competing best practices, in which situations is it best to use them?
推荐答案
一个空数组严格只等于它自己.更准确地说,计算结果为对某个特定空数组的引用的表达式仅严格等于对同一数组的另一个引用.
An empty array is strictly equal only to itself. More properly, an expression that evaluates to a reference to some particular empty array is only strictly equal to another reference to that same array.
这适用于任何类型的对象,不仅仅是数组,也不仅仅是空数组.没有内置方法可以为 ===
的相等比较提供您自己的特殊行为.
That holds for any sort of object, not just arrays, and not just empty arrays. There's no built-in way to provide your own special behavior for equality comparisons with ===
.
与 ==
的比较是另一回事,因为类型转换是隐式执行的.然而,即使使用 ==
(即,当不执行类型转换)的对象比较仍然遵循相同的规则:对一个对象的引用仅等于对相同对象的另一个引用对象.
Comparisons with ==
are another story because of the type conversions that are implicitly performed. It's still true, however, than object comparisons even with ==
(that is, when no type conversions are performed) follow the same rule: a reference to an object is only equal to another reference to the same object.
还要注意
[] === []
是 false
因为它们是两个不同的空数组.同样,
is false
because those are two different empty arrays. Similarly,
[1, 2] === [1, 2]
是 false
,原样
{a: "hello"} === {a: "hello"}
每个数组或对象初始值设定项表达式都会创建一个唯一的对象,因此即使它们看起来相同,但在 JavaScript ===
比较规则下它们并不相等.
Every array or object initializer expression creates a unique object, so even though they look the same, they're not equal under the rules of JavaScript ===
comparison.
这篇关于空数组是否严格等于 JavaScript 中的任何内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!