0

I am new to JS and have created this original problem from CodeAcademy which works. Now I wanted to put my flock of sheep into an object and access it using my sheepCounter function. I am new to accessing key/values from an object and am stuck on what I am doing wrong. Thanks in advance!

Original Code 

var sheepCounter = function (numSheep, monthNumber, monthsToPrint) {
  for (monthNumber = monthNumber; monthNumber <= monthsToPrint; monthNumber++) {
    numSheep *= 4;
    console.log("There will be " + numSheep + " sheep after " + monthNumber + " month(s)!"); 
  } 
  return numSheep;
}

New Code: 

var flock = {
    sheep: 4, 
    month: 1, 
    totalMonths: 12
};

var sheepCounter = function (counter) {
  for (counter[month] = counter[month]; counter[month] <= counter[totalMonths]; counter[month]++) {
    numSheep *= 4;
    console.log("There will be " + counter[sheep] + " sheep after " + counter[month] + " month(s)!"); 
  } 
  return counter[sheep];
}
1
  • Can you please explain the problem clearly? Commented Dec 19, 2013 at 5:53

2 Answers 2

2

Found the error in your solution:

var sheepCounter = function (counter) {
  for (counter['month'] = counter['month']; counter['month'] <= counter['totalMonths']; counter['month']++) {
    counter['sheep'] *= 4;
    console.log("There will be " + counter['sheep'] + " sheep after " + counter['month'] + " month(s)!"); 
  } 
  return counter['sheep'];
}
Sign up to request clarification or add additional context in comments.

4 Comments

However, better to use dot notation here like counter.month, counter.totalMonths, counter.sheep instead of its brackets notation. Choice is yours. :)
Thanks for the help, I see my rookie mistake :) I owe you a beer! Is there an advantage of using dot notation?
Looks cleaner, character saving like you put just dot instead of single quotes and brackets :)
This should help others as I did it with dot notation using a while loop var sheepCounter = function (counter) { while(counter.month <= counter.totalMonths) { counter.sheep *= 4; console.log("There will be " + counter.sheep + " sheep after " + counter.month + " months(s)!"); counter.month++; } };
0

You can access your Flock Object like so,

alert(flock.sheep); //4

If you have an array in an object, like

names: ['joe','tom','bob'];

You would access that like so,

alert(flock.names[0]); // joe
alert(flock.names[2]); // bob

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.