This question already has answers here:
Javascript “Variable Variables”: how to assign variable based on another variable?
                                
                                    (3个答案)
                                
                        
                6年前关闭。
            
        

我有一个Objects数组:recs6recs7recs8 ...... recs23。我想使用内部for循环在数组中添加一个因子。但是'recs + n'被解释为字符串而不是变量名。如何使它表示现有变量-rec6rec7等?

for(var n=6; n<24; n++){

    for(var m=0; m<'recs+n'.length; m++){
        hourBusyness += parseFloat(('recs'+n)[m].gtse);
    }

    hourAvgbusyness = hourBusyness / ('recs'+n).length;
    console.log(hourAvgbusyness);
}

最佳答案

使用this['recs'+n]代替('recs'+n)

09-17 04:34