Javascript 拼接去掉错误的元素

Javascript splice removes wrong element

我对这个非常简单的代码无法正常工作感到有些困惑:

 //find the index to be removed
 cardData.likeData.likeUids.forEach ((entry, index) => {
    if (entry === uid){
      uidFound = true
      uidIndex = index
      console.log ("Found uid, index is " + uidIndex)
      //console shows correct index
    }
  })
  let newLikeUids = cardData.likeData.likeUids.splice (uidIndex, 1)
  //instead of deleting the found index, the element before the index is removed... for some reason

知道为什么这不起作用吗?

你应该使用 findIndex。我不知道你的数组是什么样的,但在类似的情况下,你想从 1 和 0 的数组中删除第一个 1,你会写这样的东西:

const arr = [0,0,0,0,0,1,0,0,0];
arr.splice(arr.findIndex(e => e === 1), 1);
console.log(arr);

也许filter数组的方法可以帮到你

cardData.likeData.likeUids.filter ((entry) => {
    return entry !== uid;
});

如果您有很多 uid 需要删除

你可以试试

cardData.likeData.likeUids.filter ((entry) => {
    return uids.indexOf(entry) === -1;
});

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

我根据你写的做了一小段代码,似乎做了你想要的:

更改 UID 将决定从数据中删除什么。

let data = [1,2,3];

let uid = 1;
let foundUidIndex;

data.forEach ((entry, index) => {
    if (entry === uid){
      foundUidIndex = index;
      console.log ("Found uid, index is " + foundUidIndex)
    }
  })
 data.splice(foundUidIndex, 1);
  
console.log(data);

我注意到问题是您可能以错误的方式使用了 splice

The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place. To access part of an array without modifying it, see slice()

但是在您的代码中,您试图将 splice 的值分配给一个不起作用的值。

您可能混合了 slicesplice。我认为在这种情况下,您应该改用 slice

The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included) where start and end represent the index of items in that array. The original array will not be modified.