I have this piece of code in an angular controller that looks like so:
for (var obj in $scope.items) {
obj.done = false;
}
Here's how my $scope.items
look:
$scope.items = [
{
name: "Task #1",
done: false
},
{
name: "Task #2",
done: false
}
];
It seems weird to me that my for loop actually doesn't work. obj
isn't an object within the loop. I tried to do a console.log
of the obj
variable and it prints out the index of the array $scope.items
. Why is this so? Since this is a foreach
loop, shouldn't obj
be each of the objects inside $scope.items
?
for .. in
iterates over keys (or indexes), not values. You should do:
for (var index in $scope.items) {
$scope.items[index].done = false;
}
In general, it's considered as a bad practice to use for .. in
to iterate over arrays. You could use forEach
method instead:
$scope.items.forEach(function (item) {
item.done = false;
});
for..in
enumerates the property names of an object:
var foo = { a: 5, b: 7 };
for (var x in foo) {
console.log(x);
}
// -> a
// -> b
If you want the property values , you just look up the property in the object using the name:
var foo = { a: 5, b: 7 };
for (var x in foo) {
var value = foo[x];
console.log(value);
}
// -> 5
// -> 7
For arrays however, it's not a good idea to work with its properties to iterate over its elements. If you add a regular property to an array, such as:
var arr = [ 1, 2, 3 ];
arr.myProp = "someValue";
then myProp
will also show up in the for..in
loop, which is often unwanted. Instead, it is highly recommended to iterate over an array using a regular for
loop or using Array.forEach
:
arr.forEach(function(value, index) {
console.log(value);
})
// -> 1
// -> 2
// -> 3
What for..in
does is to iterate over attributes or properties of an object, not elements of an array. If you want to iterate over an array, then you should use normal for
loop for(var i =0; i<n; i++)..
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.