gpt4 book ai didi

javascript - 如何在javascript(angularjs)中的数组中查找数组是否为空

转载 作者:行者123 更新时间:2023-12-03 00:28:43 24 4
gpt4 key购买 nike

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

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

我得到的 2 个不同的数组:

数组1:

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

数组2:

[
[
{
"orderNumber": 1
}
]
]

我用来尝试确定“itemBag”是否为空的函数:

$scope.reproducts 就是上面提到的数组

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

我不断收到 itemBag 未定义的错误。

最佳答案

你的函数中的itemBag是什么?它在使用之前没有声明,所以当然它是未定义的。 $scope.reproducts[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.reproducts[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);
};

关于javascript - 如何在javascript(angularjs)中的数组中查找数组是否为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53960899/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com