将元素从一个数组移动到另一个数组

将元素从一个数组移动到另一个数组

问题描述:

我已尝试使以下 Stackblitz (使用ng2-dragula).在我的问题奠定了和那些被认为是选择的元素时从一个阵列移动到另一功能.我能够检测到选择了哪个元素,但无法完全移动它们(剩下了一些元素).

I've tried to make the following Stackblitz which use ng2-dragula. My problem laid in the moveback() and moveto() function which are supposed to move from one array into another when the element was selected. I was able to detect which element was selected but unable to move them completely (some element was left over).

相关代码:

  moveback() {
    let target = document.getElementsByClassName('target');
    for (let i = 0; i < target.length; i++) {
      if (target[i].className.includes('ex-over')) {
        this.removeClass(target[i], 'ex-over');
        this.data.push({ name: target[i].innerHTML });
        this.target.splice(i, 1);
      }
    }
  }

  moveto() {
    let target = document.getElementsByClassName('data');
    for (let i = 0; i < target.length; i++) {
      if (target[i].className.includes('ex-over')) {
        this.removeClass(target[i], 'ex-over');
        this.target.push({ name: target[i].innerHTML });
        this.data.splice(i, 1);
      }
    }
  }

我发现了两个 related(1)

I've found two related(1), related(2) question which asks similar thing but it's not working in my case. My approach was detecting either the element contains a certain class name then remove the class and move them to another array and remove it from the original array. But it's not working like intended.

如下更新您的for条件.

for (let i = target.length - 1; i >= 0; i--) {...}

与您的逻辑有关的问题是,如果选择2nd & 3rd元素并应用moveto,则对于2nd元素,它将正常工作.但是随后您的实际this.target数组将被更改.现在,由于您的行this.target.splice(i, 1);3rd元素将变为2nd.因此,当您在for循环迭代中移动3rd元素时,它实际上会将4th移了一个.

The issue with your logic is, If you select 2nd & 3rd element and apply moveto then for 2nd element it will work fine. But then in your actual this.target array will be changed. Now 3rd element will become 2nd because of your line this.target.splice(i, 1);. So when you move 3rd element in for loop iteration, it will actually move 4th one.

在此处检查更新的小提琴