2013-12-19 19 views
0

我是JS新手,並從CodeAcademy工作中創建了這個原始問題。現在我想將我的羊羣放入一個物體中,並使用我的綿羊計數器功能訪問它。我是新來的訪問對象的鍵/值,並堅持我做錯了什麼。提前致謝!使用javascript訪問函數中的對象

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

您能否請您清楚解釋問題? – thefourtheye

回答

2

在您的soluti中發現錯誤上:

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

但是,最好在這裏使用點符號,例如counter.month,counter.totalMonths,counter.sheep而不是其括號符號。選擇是你的。 :) – ram

+0

感謝您的幫助,我看到我的菜鳥錯誤:)我欠你一杯啤酒!使用點符號有沒有優勢? – jstone

+0

看起來更乾淨,字符保存像你把點而不是單引號和括號:) – ram

0

您可以訪問你的羊羣對象像這樣,

alert(flock.sheep); //4 

如果你有一個對象數組,像

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

你會訪問像這樣,

alert(flock.names[0]); // joe 
alert(flock.names[2]); // bob 
相關問題