0

我想复制数组中的 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

4 回答 4

4

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

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

神奇之处在于模运算符 ( %)。 i可以递增到您需要的任何值,但i%3会继续按该顺序返回 0、1 和 2。

于 2013-04-02T23:08:37.127 回答
2

您可以使用这样的方法对每个项目进行深层复制(克隆。我们可以避免使用%此解决方案,因为它最终将毫无用处。

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;
}
于 2013-04-02T23:08:19.277 回答
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];
    }
}
于 2013-04-02T23:14:33.153 回答
0
while(listings.length <= 50){
    listings[listings.length] = listings[listings.length - 3]
}

对于这样的事情,我更喜欢 while 循环而不是 for 循环。

于 2013-04-02T23:09:08.983 回答