如何在数组中创建重复的对象

时间:2013-04-02 23:04:01

标签: javascript

我想复制我的数组中的3个对象,直到总共50个。我该怎么做呢?

var listings = [
    { 
        address: "123 41st St",
        bedrooms: 2,
        bathrooms: 2,
        image: "img/1bdrm_a.jpg"
    },
    { 
        address: "234 52nd St",
        bedrooms: 1,
        bathrooms: 1,
        image: "img/1bdrm_b.jpg"
    },
    { 
        address: "345 63rd St",
        bedrooms: 3,
        bathrooms: 2,
        image: "img/1bdrm_c.jpg"
    }
];

4 个答案:

答案 0 :(得分:4)

这个循环应该可以解决问题:

for (var i = 3; i < 50; i++) {
  listings[i] = listings[i%3];
}

神奇之处在于模块化运算符(%)。 i可以增加到您需要的任何内容,但i%3将按此顺序返回0,1和2。

答案 1 :(得分:2)

您可以使用方法like this对每个项目进行深层复制(克隆)。我们可以避免将%用于此解决方案,因为它最终没有用处。

jsFiddle

var i = 0;
while (listings.length < 50) {
    listings[listings.length] = clone(listings[i++]);
}
console.log(listings);


//https://stackoverflow.com/a/122190/1156119
function clone(obj){
    if(obj == null || typeof(obj) != 'object')
        return obj;

    var temp = obj.constructor(); // changed

    for(var key in obj)
        temp[key] = clone(obj[key]);
    return temp;
}

答案 2 :(得分:0)

while(listings.length <= 50){
    listings[listings.length] = listings[listings.length - 3]
}

我喜欢while循环到for循环这样的东西。

答案 3 :(得分:0)

var listings = [
    { 
        address: "123 41st St",
        bedrooms: 2,
        bathrooms: 2,
        image: "img/1bdrm_a.jpg"
    },
    { 
        address: "234 52nd St",
        bedrooms: 1,
        bathrooms: 1,
        image: "img/1bdrm_b.jpg"
    },
    { 
        address: "345 63rd St",
        bedrooms: 3,
        bathrooms: 2,
        image: "img/1bdrm_c.jpg"
    }
];
var len=listings.length;
for(var i=0;i<listings.length;i++){
    for(var j=i;j<50;j+=len){
        listings[j]=listings[i];
    }
}