0

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);
2
  • 1
    You have a return in your for loop, so it will only run once Commented Nov 29, 2016 at 12:43
  • because you write return in the for block! Commented Nov 29, 2016 at 12:43

5 Answers 5

2

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?

Sign up to request clarification or add additional context in comments.

1 Comment

Are you OK doing that (creating the new array and appending), or do you need some help?
1

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

Comments

1

Your return in the for loop will exit the function.

You meant to write array[i].addCat(); as the statement, surely?

Comments

0

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,

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.