为什么我不能用array == []来检查数组是否为空? [英] Why can't I check if an array is empty with array == []?

查看:82
本文介绍了为什么我不能用array == []来检查数组是否为空?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是来自CodeWars的一个问题,名为正数计数/负数之和。它说:

This is a question from CodeWars that is named "Count of positives/sum of negatives". It says:


如果输入数组为空或null,则返回一个空数组

If the input array is empty or null, return an empty array

要检查数组是否为空,我决定检查它是否为空数组。当我尝试这样做时:

To check if the array is empty, I decided to check if it was an empty array. When I try to do:

if(input == [])

我没有通过测试,但如果我这样做:

I fail the test, but if I do:

if(input.length == 0)

我通过了测试。空数组应该等于 [] 对吗?为什么会有差异,这两个支票有什么区别?

I pass the test. An empty array should be equal to [] right? Why is there a difference, and what is the difference between these two checks?

我的代码如下:

function countPositivesSumNegatives(input) {
   var a = 0;
   var b = 0;
   if (input == null) {
      return []
   }
   if (input.length == 0) {
      return []
   }
   for (var i = 0; i < input.length; i++) {
      if (input[i] > 0) {
         a++;
      }
      if (input[i] < 0) {
         b += input[i];
      }
   }
   return [a, b]
}


推荐答案

问题是数组是对象。比较两个对象时,比较它们的引用。根据 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.

这篇关于为什么我不能用array == []来检查数组是否为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆