动态创建唯一的嵌套对象

时间:2014-08-19 12:47:37

标签: javascript

我需要为 我的 变量的 路线 属性创建唯一对象(路线)。这必须在循环中完成。

请查看我的代码或http://jsfiddle.net/2gk36mvo/,以便更清楚地了解我的问题。

HTML

<input type="button" value="ss" onclick="initialize();">

的javascript

var my={
        routes:{}
};

function Route(points)
{
    this.points = points;
    return this;
};

function getRoutes(routes){
    var result = [];
    for (var prop in my.routes) {
        result.push(prop);
    }
    return result.toString();
}

function initialize()
{
    // create and add objects manually
    my.routes.r0 = new Route("blabla0");
    my.routes.r1 = new Route("blabla1");
    alert(getRoutes(my.routes)); // gives 'r0,r1'

    // clear the routes for the dynamic test
    my.routes = {};

    // create and add objects dynamically
    for (i = 0; i < 2; i++) {
        //???????????? create and and add the new Route objects
    }
    alert(getRoutes(my.routes)); // must give the same result as above 'r0,r1'
}

1 个答案:

答案 0 :(得分:2)

正如cackharot在他的评论中指出的那样,你需要在for循环中使用与此类似的代码:

 for (i = 0; i < 2; i++) 
 {
    my.routes["r"+i] =  new Route("blahbla"+i);
    console.log(my.routes);
 }
相关问题