Reputation: 4093
I try to loop through the whole array and find out how 'true' they are. Now when I run the function I get some undefined-result. :( Why?
myArray = [
{text: 'hola', done: false},
{text: 'hola', done: true},
{text: 'hola', done: true},
{text: 'hola', done: false},
{text: 'hola', done: true}
];
var howMany = function(myArray){
var result;
for (var item in myArray){
if(myArray.done === true)
result++;
}
return result;
};
var items =howMany(myArray);
console.log(items) // I want to see if it's correct
Upvotes: 0
Views: 86
Reputation: 26730
a) You did not initialize the value of result
:
var result = 0;
b) This is not how you iterate over the items of an array:
for (var i = 0; i < myArray.length; i++) {
var item = myArray[i];
if (item.done === true) { // <-- "item" here, not "myArray"!
result++;
}
}
Upvotes: 5
Reputation: 145398
Check that result
variable is initialised with 0
. And there is another problem in iteration. You need to use myArray[item]
to get the value of the object property:
if (myArray[item].done === true)
Upvotes: 4
Reputation: 324640
Try initialising your variable to an actual value: var result = 0;
EDIT: Also, as per VisioN's answer, you need to check myArray[item].done
Upvotes: 1