Nataliia Shyianovska Nataliia Shyianovska - 10 days ago 6
Javascript Question

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.name = name;
obj.src = src;
obj.clicks = clicks;
return obj;
}
var getCatList = function (array) {
for (let i = 0; i < array.length; i++) {
console.log(array[i]);
return 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);

Ali Ali
Answer

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);