在 JavaScript 中循环遍历对象列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24098824/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Looping through a List of objects in JavaScript
提问by Ali Khalil
I want to loop through the student list which I received from a REST service located on a server. this list contains objects for students enrolled in a section. Each object has firstName, lastName, student ID and many other attributes, specifically an attribute called isAbsent
. Its a Boolean value where it has true if the student is absent and false if the student is present in not absent. I want to store the students IDs who are absent (have isAbsent=true
) in another String Array.
我想遍历从位于服务器上的 REST 服务收到的学生列表。此列表包含在某个部分注册的学生的对象。每个对象都有 firstName、lastName、student ID 和许多其他属性,特别是一个名为 的属性isAbsent
。它是一个布尔值,如果学生缺席则为真,如果学生不在场则为假。我想将缺席(有isAbsent=true
)的学生 ID 存储在另一个字符串数组中。
I tried this :
我试过这个:
{
//this array will store the IDs of students who are absent.
$scope.selection = [];
//$scope.studentList is the list of students for CRN=X and Date=Y
for (id in $scope.studentList) {
if ($scope.studentList.isAbsent === true) {
$scope.selection.push($scope.studentList.id);
console.log($scope.selection);
}
}
}
This code doesn't execute. I have no clue why, I guess the problem in the loop structure. Any help?
这段代码不执行。我不知道为什么,我猜是循环结构的问题。有什么帮助吗?
回答by Royi Namir
Maybe this will help?
也许这会有所帮助?
for (var i=0;i<$scope.studentList.length;i++)
{
if ($scope.studentList[i].isAbsent === true)
{
$scope.selection.push($scope.studentList[i].id);
console.log($scope.selection);
}
}
p.s. don't use for..in
with arrays. It will display an index instead of a value. It's not like C#.
ps 不要for..in
与数组一起使用。它将显示一个索引而不是一个值。它不像 C#。
回答by Chris Montgomery
Depending on what browsers you need to support (e.g. IE >= 9), I'd suggest the newer foreach
construct. I find it easier to use:
根据您需要支持的浏览器(例如 IE >= 9),我建议使用较新的foreach
构造。我发现它更易于使用:
$scope.studentList.forEach(function(value, index, array) {
if (value.isAbsent === true)
{
$scope.selection.push(value.id);
console.log($scope.selection);
}
});