简体   繁体   English

动态创建唯一的嵌套对象

[英]create unique nested objects dynamically

I need to create unique objects(Route) for the my variable's routes property. 我需要为我的变量的路线属性唯一对象(路线)。 And this has to be done in a loop . 这必须循环进行

Please check out my code blow or http://jsfiddle.net/2gk36mvo/ to have a more clear image about my problem. 请查看我的代码打击或http://jsfiddle.net/2gk36mvo/ ,以更清晰地了解我的问题。

html html

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

javascript 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'
}

As cackharot states in his comment, you need to have code similar to this in your for loop: 正如cackharot在他的评论中指出的那样,您需要在for循环中具有与此类似的代码:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM