For Loop Displays Only First Item In Array
My for loop somehome works only on first item of array but not with rest. var Cat = function ( name, src, id, clicks) { var obj = Object.create(Cat.prototype); obj.id = id; obj.
Solution 1:
You return out of the loop after the first iteration:
return array[i].addCat();
Not sure what you're trying to do - add a cat to a new array and return it?
Solution 2:
The return
statement in your for block will exit the for iteration after the first one.
var getCatList = function (array) {
for (let i = 0; i < array.length; i++) {
console.log(array[i]);
// remove return statement
// return array[i].addCat();
array[i].addCat();
}
}
var Cats = [new Cat("cat-1", "image.src", "cat_1", 0),new Cat("cat-2", "image.src", "cat_2", 0), new Cat("cat-3", "image.src", "cat_3", 0)]
getCatList(Cats);
Solution 3:
Your return
in the for
loop will exit the function.
You meant to write array[i].addCat();
as the statement, surely?
Solution 4:
No matter how many elements the array is holding
doing this
for (let i = 0; i < array.length; i++) {
console.log(array[i]);
return array[i].addCat();
}
will execute ONLY the first boucle in the loop,
Solution 5:
If you call return
within a for
loop, it will stops the execution and exits the function.
To get an array of Cats out of getCatList
method you can use Array.prototype.map():
Code:
var Cat = function (name, src, id, clicks) {
var obj = Object.create(Cat.prototype);
obj.id = id;
obj.name = name;
obj.src = src;
obj.clicks = clicks;
return obj;
},
getCatList = function (array) {
return array.map(function (el) {
return el;
});
},
Cats = [new Cat("cat-1", "image.src", "cat_1", 0), new Cat("cat-2", "image.src", "cat_2", 0), new Cat("cat-3", "image.src", "cat_3", 0)];
console.log(getCatList(Cats));
ES6:
let getCatList = array => array.map(el => el);
Post a Comment for "For Loop Displays Only First Item In Array"