繁体   English   中英

javascript forloop,将当前项目记录在array中,并将其余项目与array

[英]javascript forloop, log the current item in array and array with the rest of items

所以我有一系列看起来像这样的物品:

var receivedQuery = [   { 'ingredients.ingredient': /^what$/i },
                        { 'ingredients.ingredient': /^you$/i},
                        { 'ingredients.ingredient': /^said$/i},
                        { 'ingredients.ingredient': /^about$/i},
                        { 'ingredients.ingredient': /^that$/i}
                    ];

我正在尝试登录控制台中array的每个项目,而其余数组中没有当前项目的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/

这是因为splice返回包含删除的元素的数组。

var splicedQuery = receivedQuery.slice();

for (var i = 0, max = splicedQuery.length; i < max; i++) {
    console.log(splicedQuery.splice(0, 1), splicedQuery);
};

使用slice将创建的浅表副本receivedQuery阵列。

工作示例: http : //jsfiddle.net/VUetk/1/

如果要显示当前元素,以及不使用当前元素时整个数组的外观,则必须执行以下操作

for (i = 0, max = receivedQuery.length; i < max; i++) {
    var copy = receivedQuery.slice(0);
    console.log(copy.splice(i, 1), copy);
};

小提琴

您必须进行复制,因为splice会修改您传入的数组。我们希望原始数组保持原样。

使用过滤功能:

for (i = 0, max = receivedQuery.length; i < max; i++) {
  var filtered = receivedQuery.filter(function(elem, index) {
    return index != i;
  });
  console.log( receivedQuery[i], filtered );
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM