空数组是否严格等于JavaScript中的任何内容

空数组是否严格等于JavaScript中的任何内容

本文介绍了空数组是否严格等于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中的任何内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 17:04