所以我有一系列看起来像这样的项目:
var receivedQuery = [ { 'ingredients.ingredient': /^what$/i },
{ 'ingredients.ingredient': /^you$/i},
{ 'ingredients.ingredient': /^said$/i},
{ 'ingredients.ingredient': /^about$/i},
{ 'ingredients.ingredient': /^that$/i}
];
我正在尝试在数组中的每个项目中登录控制台,而其余的数组中没有当前项目的for循环。 我尝试使用拼接方法这样做:
var splicedQuery = receivedQuery;
for (i = 0, max = receivedQuery.length; i < max; i++) {
var position = i;
splicedQuery = splicedQuery.splice(position, 1);
console.log( receivedQuery[i], splicedQuery );
};
但是我没有收到它,因为我想要:
{ 'ingredients.ingredient': /^you$/i } [ { 'ingredients.ingredient': /^what$/i } ]
{ 'ingredients.ingredient': /^said$/i } []
{ 'ingredients.ingredient': /^about$/i } []
{ 'ingredients.ingredient': /^that$/i } []
undefined []
我希望它输出如下内容:
{ 'ingredients.ingredient': /^what$/i }, [ { 'ingredients.ingredient': /^you$/i}, { 'ingredients.ingredient': /^said$/i}, { 'ingredients.ingredient': /^about$/i}, { 'ingredients.ingredient': /^that$/i} ]
{ 'ingredients.ingredient': /^you$/i }, [ { 'ingredients.ingredient': /^what$/i}, { 'ingredients.ingredient': /^said$/i}, { 'ingredients.ingredient': /^about$/i}, { 'ingredients.ingredient': /^that$/i} ]
{ 'ingredients.ingredient': /^said$/i }, [ { 'ingredients.ingredient': /^what$/i}, { 'ingredients.ingredient': /^you$/i}, { 'ingredients.ingredient': /^about$/i}, { 'ingredients.ingredient': /^that$/i} ]
........
我不确定如何做到这一点以正确的方式控制它...什么是最好的方法?也许使用除splice()
或?
您可以在jsfiddle中查看和编辑我的情况:http://jsfiddle.net/RgGzE/
答案 0 :(得分:1)
这是因为splice
返回一个包含已删除元素的数组。
var splicedQuery = receivedQuery.slice();
for (var i = 0, max = splicedQuery.length; i < max; i++) {
console.log(splicedQuery.splice(0, 1), splicedQuery);
};
使用slice
将创建receivedQuery
数组的浅表副本。
答案 1 :(得分:0)
如果你想显示当前元素,以及没有当前元素的整个数组的样子,你必须做这样的事情
for (i = 0, max = receivedQuery.length; i < max; i++) {
var copy = receivedQuery.slice(0);
console.log(copy.splice(i, 1), copy);
};
您必须制作副本,因为splice
会修改您传入的数组。我们希望原始数据完好无损。
答案 2 :(得分:0)
使用过滤功能:
for (i = 0, max = receivedQuery.length; i < max; i++) {
var filtered = receivedQuery.filter(function(elem, index) {
return index != i;
});
console.log( receivedQuery[i], filtered );
};