2013-01-31 82 views
-1

試圖讓這個在JS創建工作:在對象引用變量使用自定義構造函數

var calculate = function(votesA, votesB, votesC) { 

    var total = votesA + votesB + votesC; 

    function Results(resultsA, resultsB, resultsC) { 
     this.resultsA = resultsA; 
     this.resultsB = resultsB; 
     this.resultsC = resultsC; 
    } 

    var curResults = new Results(votesA, votesB, votesC); 

    curResults.resultsA = (votesA/total) x 100; 
    curResults.resultsB = (votesB/total) x 100; 
    curResults.resultsC = (votesC/total) x 100; 

    console.log(curResults.resultsA, curResults.resultsB, curResults.resultsC); 
} 

calculate(5,4,8); 
calculate(5,6,8); 
calculate(6,8,9); 

不知道爲什麼它不工作,但我覺得這是值得做的怎麼樣我參考curResults中的變量

+0

你能告訴我們你想做什麼嗎? – polin

回答

2

JavaScript的乘法運算符是*而不是x

在以下幾行x是給你一個 「意外的標識符」 錯誤:

curResults.resultsA = (votesA/total) x 100; 
curResults.resultsB = (votesB/total) x 100; 
curResults.resultsC = (votesC/total) x 100; 

他們於是更改爲:

curResults.resultsA = (votesA/total) * 100; 
curResults.resultsB = (votesB/total) * 100; 
curResults.resultsC = (votesC/total) * 100; 

Not sure why it isn't working, but I feel like it is something to do with how I am referencing the variables incurResults

不,這部分是好的。儘管如此,如果您立即覆蓋上面三行中的那些值,那麼在您的Results()構造函數中分配this.resultsA = resultsA;(和resultsBC)沒有意義。

+0

感覺像這樣一個白癡哈哈謝謝 – Kayra

+0

我花了一些時間來發現它 - 起初我只是自然地閱讀每個「x」作爲乘法...... – nnnnnn

相關問題