繁体   English   中英

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);

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

splice() 方法通过删除或替换现有元素和/或在适当位置添加新元素来更改数组的内容。 要访问数组的一部分而不修改它,请参阅 slice()

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

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

slice() 方法将数组的一部分的浅拷贝返回到一个新数组 object 中,该数组从开始到结束(不包括结束)选择,其中开始和结束表示该数组中项目的索引。 原始数组不会被修改。

也许 Array 的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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM