记前端知识--数组元素的相关操作

数组中元素的操作

const arr = [1, 2, 3, 4];
this.removeByValue(4);
console.log(arr); // [1, 2, 3]
this.addByValue(6);
console.log(arr); // [1, 2, 3, 6]
复制代码

1、关于数组元素的减少

removeByValue = (val) => { // 减少指定的数组元素
    for (let i = 0; i < arr.length; i += 1) {
      if (arr[i] === val) {
        this.arr.splice(i, 1);
        return;
      }
    }
  }
  
复制代码

2、数组的元素为对象时,可以根据唯一key,来进行确认减少(比第一种简便)

const newData = this.arr.filter(item => item.key !== key);
复制代码

3、关于数组元素的增加

 addByValue = (val) => { // 增加元素
    this.arr.push(val);
  }
复制代码

4、有数组中,取出key值为K的对象元素

const target = arr.find(item => item.key === no);
复制代码

5、两个数组之间,进行相关的操作

const arr1 = [1,2,3];

const arr2 = [3,4,5];

// 并集

const union = Array.from(new Set([...arr1,...arr2]));    // union = [1,2,3,4,5]

// 交集

const intersection = Array.from(new Set([...arr1].filter(x => new Set(arr2).has(x))));   // intersection = [3]

// 差集

const difference1 = Array.from(new Set([...arr1].filter(x => !new Set(arr2).has(x))));    // difference1 = [1,2]

const difference2 = Array.from(new Set([...arr2].filter(x => !new Set(arr1).has(x))));    // difference2 = [4,5]
复制代码

6、置换数组之间的位置(实战:在table中,可以置换位置)

  • 置换函数:
  swapItems = (arr, index1, index2) => {
    const arrData = arr;
    arrData[index1] = arrData.splice(index2, 1, arrData[index1])[0];
    return arr;
  }
复制代码
  • 向前移动(在表格中展示为向上移动)
upRecord(no) {
    const newData = this.state.selectedMaterialList.slice(0);
    const target = newData.find(item => item.key === no);
    const index = newData.indexOf(target);
    if (index === 0) {
      message.warn('此模板为第一条,无法上移', 1.5);
    } else {
      const data = this.swapItems(newData, index, index - 1);
      this.setState({ selectedMaterialList: data });
    }
  }
复制代码
  • 向前移动(在表格中展示为向上移动)
downRecord(no) {
    const newData = this.state.selectedMaterialList.slice(0);
    const target = newData.find(item => item.key === no);
    const index = newData.indexOf(target);
    if (index === newData.length - 1) {
      message.warn('此模板为最后一条,无法下移', 1.5);
    } else {
      const data = this.swapItems(newData, index, index + 1);
      this.setState({ selectedMaterialList: data });
    }
  }
复制代码
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值