2014-05-06 57 views
1

我正在學習JavaScript,現在我正在將函數放入對象中。我一直收到關於玩雜耍功能的評估錯誤。有人能解釋我做錯了什麼嗎?謝謝!理解對象中的JS函數時遇到的問題

var juggler = { 
    itemCount: 0 
    juggle: function() { 
    this.itemCount += 1; 
    var fate = parseInt(Math.random() * 10); 
    if (this.itemCount > 2 && fate % 2 === 0) { 
     this.drop(); 
     return 1; 
    } 
    else { 
     return 0; 
    } 
    } 
    drop: function() { 
    console.log('ah!'); 
    this.itemCount = this.itemCount - 1; 
    } 
}; 

juggler.juggle(); 
juggler.juggle(); 
console.log('Juggler should be juggling two items:', juggler.itemCount); 

var dropCount = 0; 

dropCount += juggler.juggle(); 
dropCount += juggler.juggle(); 
dropCount += juggler.juggle(); 

console.log('Total number of items should be 5:', juggler.itemCount + dropCount); 
console.log('Juggler should be juggling at least two items:', juggler.itemCount); 
+0

不是你錯誤的原因,但你不應該在數字上使用'parseInt'。你想'Math.floor()' – Bergi

+0

注意。謝謝! – splatoperator

回答

1

使用Javascript {}表示一個對象。所以,你正在創建一個名爲juggler與性能itemCountjuggledrop項目等。因此,你需要將這些屬性用逗號分隔:

itemCount: 0, 
juggle: function() { 

您可以像地圖把它(語法)在Java中,如果有幫助。

+1

非常感謝。 – splatoperator

3

對象上的屬性必須用逗號分隔。

var juggler = { 
    itemCount: 0, 
// -----------^ 
    juggle: function() { 
    // code here 
    }, 
//^
    drop: function() { 
    // code here 
    } 
// note no comma on last item 
}; 
+0

啊,我明白了。非常感謝你的幫助! – splatoperator

相關問題