splice

💜splice

定义

删除数组指定位置、指定个数的元素,并可插入新元素,返回被删除的元素。

原数组也会改变。

语法

arrayObject.splice(index,howmany,item1,.....,itemX)
参数 描述
index 必需。整数,规定添加/删除项目的位置,使用负数可从数组结尾处规定位置。
howmany 必需。要删除的项目数量。如果设置为 0,则不会删除项目。
item1, ..., itemX 可选。向数组添加的新项目。
var arr = [1,2,3,4]
console.log(arr.splice(1,1));// [2]
console.log(arr); // [1,3,4]

在实际项目的使用中发现,splice删除后没有更新页面

解决方法1:换成filter

百度到的解决方法

arr.filter((item,itemindex)=> itemindex!=index)

解决方法2:拷贝一份

removeEntities = (entities) => {
const { ownerEntitiesList } = this.state;
const newData = [...ownerEntitiesList];     //这里是重点,直接拷贝一份出来,
  newData.map((item, index) => {
    if (item === entities) {
      newData.splice(index, 1);
      this.setState({
        ownerEntitiesList: newData,   //直接setState这个改变后的数组
      });
    }
  });
 };
posted @ 2020-11-23 15:54  wattmelon  阅读(396)  评论(0编辑  收藏  举报