gpt4 book ai didi

javascript - 如何使用 for 循环迭代 Angular $scope 变量

转载 作者:行者123 更新时间:2023-12-01 04:03:23 26 4
gpt4 key购买 nike

我想使用 for 循环而不是使用 foreach 来迭代数组,因为 foreach 中我无法打破循环。但在 for 循环中我得到 $scope.items[i] 为未定义!这里我根据条件动态地在数组中添加值。

$scope.items= [{
name: 'abhishek',
credit: 1233,
debit: 0,
balance: 12
}];
for (var i = 1; i <= $scope.items.length; i++) {
console.log($scope.items.length);
if ($scope.selectedName.value === $scope.items[i].name) {
console.log($scope.items[i].name + "forif" + true);
break;
}
else {
console.log($scope.items[i].name + "forelse " + false);
break;
}
}

最佳答案

发生这种情况是因为您在索引 1 处开始 for 循环。数组在 Javascript 中是 0 索引的,因此更改 i = 1i = 0并且您应该能够访问数组中的对象。

因此您的for循环应使用小于 ( < ) 运算符而不是 ( <= ) 检查索引是否小于数组的长度。

来源:MDN

JavaScript arrays are zero-indexed: the first element of an array is at index 0, and the last element is at the index equal to the value of the array's length property minus 1.

这段代码工作正常(我不知道你如何设置 selectedName ,但我只是在我的示例中对其进行了硬编码:

$scope.selectedName = {value: 'abhishek'};

$scope.items= [{
name: 'abhishek',
credit: 1233,
debit: 0,
balance: 12
}];

for (var i = 0; i <= $scope.items.length; i++) {
console.log($scope.items.length);
if ($scope.selectedName.value === $scope.items[i].name) {
console.log($scope.items[i].name + "forif" + true);
break;
}
else {
console.log($scope.items[i].name + "forelse " + false);
break;
}
}
}

关于javascript - 如何使用 for 循环迭代 Angular $scope 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42010631/

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