簡體   English   中英

動態創建唯一的嵌套對象

[英]create unique nested objects dynamically

我需要為我的變量的路線屬性唯一對象(路線)。 這必須循環進行

請查看我的代碼打擊或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'
}

正如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