迭代数组并使用splice()更新父数组?

时间:2013-03-06 15:44:46

标签: javascript jquery iteration

当用户点击按钮时,我抓住availableTags数组,将其存储在新的var tagsToWorkWith中。然后我遍历tagsToWorkWith并在每一行上运行moveTag(),以便移动availableTags中的每个标记。

moveTag()内,我正在使用availableTagssplice()删除该行。但是,出于某种原因,这是从tagsToWorkWith中删除行,这导致我的for()函数仅在每隔一行运行moveTag()

为什么splice()tagsToWorkWith删除行?我明确设置tagsToWorkWith等于原始availableTags以避免此问题,但这不是似乎工作正常。

以下代码与http://jsfiddle.net/EdnxH/

处的错误一起运行
var availableTags = [{"label":"Label A","value":"1"},{"label":"Label B","value":"2"}, {"label":"Label C","value":"3"}];

$(document).on('click', '#clickButton', function () {
    var tagsToWorkWith = availableTags;                         
    for(var countera=0; countera< tagsToWorkWith.length; countera++) {
        alert(tagsToWorkWith[countera].label);
        moveTag(tagsToWorkWith[countera].label, tagsToWorkWith[countera].value);
        //This should match the first alert label, since we haven't increased the counter yet. But, for some reason, moveTag()'s splice() removes the row from tagsToWorkWith.
        alert(tagsToWorkWith[countera].label);
    }   
});

function moveTag(itemToMove, itemToMoveValue) {
   var selectedTagArrayIndex = -1;    
   for(var counter=0; counter< availableTags.length; counter++) {
       if (availableTags[counter].value == itemToMoveValue) {
           selectedTagArrayIndex = counter;
       }
   } 
   if (selectedTagArrayIndex > -1)  {
       availableTags.splice(selectedTagArrayIndex, 1);
   }
}

1 个答案:

答案 0 :(得分:4)

数组是对象,在变量之间分配引用时,对象不会被“深度复制”。因此,两个变量都引用完全相同的对象。

因此:

var a = ["hello", "world"];
var b = a;
a[2] = "again";
alert(b[2]); // "again" because "a" and "b" are the same object

如果要复制数组,可以使用:

var b = a.slice(0);