我正在尝试迭代数组
[1,2,3,4,5,6]
我想将它们存储在一个对象中,以便:
[
{1},
{1,2},
{1,2,3},
{2,3,4},
{3,4,5},
{4,5,6}
]
您可能会注意到,如果达到限制3,则首先删除要在数组中推送的第一个元素。
我这样做:
var given = [1,2,3,4,5,6];
var limit = 3;
var start = 1;
var result = [];
for (var i = 0; i < given.length; i++) {
var j = 0;
while(j <= start) {
j++;
if(start <= limit) {start++};
result.push(given[i]);
}
};
console.log(result);
似乎我的回答是超级错误,我仍然坚持将它逐一推动然后增加。所以我还没有想到要替换最古老的元素。
修改
此外,我正在考虑不移动数组并将新值放到最后,而是替换值并维护其索引......
我的意思是
[
{1},
{1,2},
{1,2,3},
{4,2,3},
{4,5,3},
{4,5,6}
]
答案 0 :(得分:3)
尝试
var given = [1, 2, 3, 4, 5, 6];
var limit = 3;
var start = 1;
var result = [], rec = [];
for (var i = 0; i < given.length; i++) {
rec = rec.slice(0);
if(rec.length == limit){
rec.shift();
}
rec.push(given[i]);
result.push(rec)
}
console.log(JSON.stringify(result));
演示:Fiddle
O / P
[[1],[1,2],[1,2,3],[2,3,4],[3,4,5]]
<强>更新强>
var given = [1, 2, 3, 4, 5, 6];
var limit = 3;
var start = 1;
var result = [],
rec = [];
for (var i = 0; i < given.length; i++) {
rec = rec.slice(0);
rec[i % limit] = given[i]
result.push(rec)
}
console.log(JSON.stringify(result));
演示:Fiddle
O / P
[[1],[1,2],[1,2,3],[4,2,3],[4,5,3],[4,5,6]]