jstone
jstone

Reputation: 445

access an object in a function using javascript

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];
}

Upvotes: 0

Views: 74

Answers (2)

Dhanu Gurung
Dhanu Gurung

Reputation: 8840

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'];
}

Upvotes: 2

Alan Bowen
Alan Bowen

Reputation: 1048

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

Upvotes: 0

Related Questions