使用javascript访问函数中的对象

使用javascript访问函数中的对象,javascript,object,Javascript,Object,我是JS新手,我从CodeAcademy创建了这个原始问题。现在我想把我的羊群放到一个对象中,并使用sheepCounter函数访问它。我不熟悉从对象访问键/值,并且对自己做错的事情耿耿于怀。提前谢谢 Original Code var sheepCounter = function (numSheep, monthNumber, monthsToPrint) { for (monthNumber = monthNumber; monthNumber <= monthsToPrin

我是JS新手,我从CodeAcademy创建了这个原始问题。现在我想把我的羊群放到一个对象中,并使用sheepCounter函数访问它。我不熟悉从对象访问键/值,并且对自己做错的事情耿耿于怀。提前谢谢

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];
}
原始代码
var sheepCounter=函数(numSheep、monthNumber、monthsToPrint){

对于(monthNumber=monthNumber;monthNumber您可以像这样访问Flock对象

alert(flock.sheep); //4
alert(flock.names[0]); // joe
alert(flock.names[2]); // bob
如果对象中有一个数组,如

names: ['joe','tom','bob'];
你可以这样访问它

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

在解决方案中发现错误:

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'];
}
var sheepCounter=函数(计数器){

对于(counter['month']=counter['month'];counter['month']您能清楚地解释这个问题吗?但是,最好在这里使用点符号,如counter.month、counter.totalMonths、counter.sheep,而不是括号符号。选择权归您。谢谢您的帮助,我发现了我的新手错误:)我欠你一杯啤酒!使用点表示法有什么好处吗?看起来更干净,节省字符,就像你只使用点而不是单引号和括号:)这应该会帮助其他人,就像我使用while循环
var sheepCounter=function(counter){while(counter.month)使用点表示法一样