当用户单击按钮时,我将抓取availableTags
数组,将其存储在一个新的var tagsToWorkWith
. 然后我迭代tagsToWorkWith
并moveTag()
在每一行上运行,以便移动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);
}
}