如何在javascript(angularjs)中的数组中查找空数组

如何在javascript(angularjs)中的数组中查找空数组,javascript,arrays,angularjs,function,Javascript,Arrays,Angularjs,Function,我目前正在尝试查找对象中是否设置了对象属性“itemBag” 我遇到的问题是,我从api获得了两个不同的数组,并且属性“itemBag”不包含在对象中,因此我得到了一个“未定义”错误 我得到的两个不同数组: 阵列1: [ [ { "orderNumber": 1, "itemBag": [ { "size": 10000, "name": "hello.pdf", } ]

我目前正在尝试查找对象中是否设置了对象属性“itemBag”

我遇到的问题是,我从api获得了两个不同的数组,并且属性“itemBag”不包含在对象中,因此我得到了一个“未定义”错误

我得到的两个不同数组:

阵列1:

[
  [
    {
      "orderNumber": 1,
      "itemBag": [
        {
          "size": 10000,
          "name": "hello.pdf",
        }
      ]
    }
  ]
]
阵列2:

[
  [
    {
      "orderNumber": 1
    }
  ]
]
我用于尝试确定“itemBag”是否为空的函数:


$scope.reproductions是上面提到的数组

$scope.checkFirstDesignContainerIsEmpty = function() {
    var containerIsEmpty;
    if($scope.reproductions[0][0].includes(itemBag)) {
      containerIsEmpty = true;
    }
    return containerIsEmpty;
};

我一直收到一个错误,即itemBag未定义。

您的函数中的
itemBag
是什么?它在使用前没有声明,所以它当然是未定义的
$scope.reproductions[0][0]
也不是一个数组,它是一个对象,因此尝试调用
includes
之类的数组函数是行不通的

$scope.checkFirstDesignContainerIsEmpty = function() {
    var containerIsEmpty;
    if($scope.reproductions[0][0].includes(itemBag)) { // itemBag hasn't been declared, so is undefined
      containerIsEmpty = true;
    }
    return containerIsEmpty;
};
要测试
$scope.reproductions[0][0]
对象是否没有
itemBag
属性,或者是否有且为空:

$scope.checkFirstDesignContainerIsEmpty = function() {
    var containerIsEmpty = true;

    // test if itemBag key exists and value has truthy length value
    const { itemBag } = $scope.reproductions[0][0];
    if(itemBag && itemBag.length) {
      containerIsEmpty = false;
    }
    return containerIsEmpty;
};
或者更简洁地说:

$scope.checkFirstDesignContainerIsEmpty = function() {
    const { itemBag } = $scope.reproductions[0][0];
    return !(itemBag && itemBag.length);
};

尝试在itemBag周围添加引号:

$scope.checkFirstDesignContainerIsEmpty = function() {
  var containerIsEmpty;
  if($scope.reproductions[0][0].includes('itemBag')) { // Added quotes here
    containerIsEmpty = true;
  }
  return containerIsEmpty;
};

(parent.childArray | |【】)。length==0
是测试数组$scope.reproductions是否为上述数组的简单方法是的,
$scope.reproductions
已定义,但使用方式不正确。如前所述,您正在搜索复制数组,以查找与
itemBag
匹配的值,但未定义
itemBag
。它也不起作用,因为
复制[0][0]
不是数组,它是对象。$scope.reproductions[0][0]。includes不是函数是我得到的错误我的错误!只能在阵列上使用
包含
。尝试查看对象是否具有属性时,必须使用
hasOwnProperty
。请看这里: