且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么我不能用array == []来检查数组是否为空?

更新时间:2023-11-29 08:21:52

问题是数组是对象。比较两个对象时,比较它们的引用。根据 MDN文档

The problem is that arrays are objects. When you compare two objects, you compare their references. Per the MDN documentation:


Equality(==)



如果两个操作数都是对象,然后JavaScript比较当操作数引用内存中相同对象时相等的内部引用。

Equality (==)

If both operands are objects, then JavaScript compares internal references which are equal when operands refer to the same object in memory.

因为两个数组实例不在t必须具有相同的参考,检查失败。只需在控制台中尝试:

Since two instances of arrays don't necessarily have the same reference, the check fails. Just try this in the console:

> [] == []
false

两个阵列看似具有相同的内容(或缺乏它不相等。那是因为没有检查内容,而是参考。这两个数组是单独的实例,并引用内存中的不同位置,因此检查的结果为false。

Two arrays seemingly with the same content (or lack thereof) are not equal. That's because content is not checked, but reference. These two arrays are separate instances and refer to different places in memory, thus the check evaluates to false.

另一方面,只检查长度,如果为零则检查数组是否为空。 length 属性表示数组 1 中的内容量,并且是每个数组的一部分。由于它是每个数组的一部分并反映了数组中的数据量,因此您可以使用它来检查数组是否为空。

On the other hand, just checking the length, and if it is zero checks if the array is empty or not. The length property signifies the amount of content in an array1 and is part of every array. Since it is part of every array and reflects the amount of data in the array, you can use it to check if the array is empty or not.

1 但要注意 稀疏数组 ,如 RobG 在评论中。可以使用 new Array(N)创建这样的数组,它将为您提供一个空数组,但长度为N.

1 Beware, though, of sparse arrays as mentioned by RobG in the comments. Such arrays can be created with new Array(N) which will give you an empty array, but with length N.