0

当用户单击按钮时,我将抓取availableTags数组,将其存储在一个新的var tagsToWorkWith. 然后我迭代tagsToWorkWithmoveTag()在每一行上运行,以便移动availableTags.

在里面moveTag(),我正在从availableTags使用中删除该行splice()。但是,由于某种原因,这会从 中删除该行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);
   }
}
4

1 回答 1

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);
于 2013-03-06T15:46:49.127 回答