When I have objects in Array like
var bookIndex = [{
id: '1',
title: 'First title',
description: 'This is my first title'
}, {
id: '2',
title: 'Second title',
description: 'This is my second title'
}];
then loop through array using for()
function getBook(bookId){
for (var i = 0; i < bookIndex.length; i++) {
if (bookIndex[i].id === bookId) {
return bookIndex[i];
}
}
return undefined;
};
I wonder how to use other loop method, to get same result. Ex. forEach. I try to use something like this but it couldn't get return object I want.
function getBook(bookId) {
bookIndex.forEach(function () {
if (bookId === bookIndex.id) {
return bookId;
}
return undefined;
});
};
loopor arraysearch?getBook()return a book or an index? if just the inde, the you have already one, then you need only true or false.Array.prototype.find()but if you need all occurrences thenArray.prototype.filter()is your friend.