0

如何为变量名分配索引?例如,project0、project1、project2 等?

for (var i=0; i<data.length; i++)
{
    var project+i = new GanttProjectInfo(1, "Applet redesign", new Date(2010, 5, 11));
    var parentTask+i = new GanttTaskInfo(1, "Old code review", new Date(2010, 5, 11), 208, 50, "");
    project1.addTask(parentTask+i);
    // Load data structure        
    ganttChartControl.addProject(project+i);
    // Build control on the page
}
4

2 回答 2

2

正如@JaredFarrish 建议的那样,您可以简单地使用数组来存储所有项目。在变量被覆盖之前创建它们并将它们添加到数组中:

var projects = [];
for (var i = 0; i < data.length; i++) {
    var project = new GanttProjectInfo(1, "Applet redesign", new Date(2010, 5, 11));
    var parentTask = new GanttTaskInfo(1, "Old code review", new Date(2010, 5, 11), 208, 50, "");
    project.addTask(parentTask);
    ganttChartControl.addProject(project);

    // Push this project to the array to save it
    projects.push(project);
}

// Need to access the first project?
projects[0].foo();
于 2012-08-11T14:18:15.563 回答
0

使用 eval()

eval(("变量名" + i) + " = " + 5 + i);

但并不真正推荐使用 eval ,总有办法解决你想做的事情。

于 2012-08-11T14:32:18.307 回答