2014-09-11 33 views
0

我要縮短這些線路如何在AS3中使用值作爲實例名稱?

var upgradethis = "u3"; 

if (nev == "u1"){ 
    mM.u1.count.text=minionCounter[lvl]; 
} 
if (nev == "u2"){ 
    mM.u2.count.text=minionCounter[lvl]; 
} 

我怎麼能代替「U1」和「U2」與「upgradethis」的價值?

並在此使用:

mM。 upgradethis's value .count.text = minionCounter [lvl];

(替換此代碼U2爲 「upgradethis」 的值)

+3

只要嘗試'mM [upgradethis] .count.text' – Cherniv 2014-09-11 13:28:06

+0

謝謝,工作! :) – 2014-09-11 13:34:59

+3

@Cherniv不要在評論中回答,在答案中回答。 – Pimgd 2014-09-11 13:37:16

回答

3

Question with no answers, but issue solved in the comments (or extended in chat)

使用mM[upgradethis].count.text來解決這個問題。

歸因於Cherniv, who posted it here的解決方案。

請注意,如果您不檢查屬性是否存在,則可以運行到TypeError #1010: A term is undefined and has no properties。你可以使用hasOwnProperty(語法if(mm.hasOwnProperty(upgradethis)))。

+1

我還建議通過添加'if mM.hasOwnProperty(upgradethis)'來確保使用動態屬性名稱時該屬性存在。這是一個很好的做法,即使你很確定那裏的財產在那裏。 – evilpenguin 2014-09-12 07:45:22