后台管理系统中常用的es6方法

后台管理系统中最常见的莫过于增删改查,常用的方法有map(渲染一个下拉框),includes(与indexOf类似,但比他强大,它们既可以用于数组也可以用于字符串),find&&findIndex(返回第一个满足条件的值,没有则返回undefined),filter(返回满足条件的数据),forEach(for循环的简化版),

this.state = {
    
    
   count: 1,
   dataSource: []
}
const newData = {
    
    
  key: count,
  name: `nick${
      
      count}`,
  age: 18,
};

1.增加一般使用push方法向数组的尾部添加元素,但会改变原数组,可以用数组结构赋值的方式

//React写法
const {
    
     count, dataSource } = this.state;
this.setState({
    
     
  dataSource:[...dataSource, newData],
  count: count + 1,
});

2.删除使用splice方法,先是找到自身的索引值,再用splice方法删除,可以用filter方法,也可以用slice

const index = newData.findIndex(item => item.key === row.key);
const num = 1  //删除的个数
newData.splice(index, num)
 //删除一个元素
const newArr = array.filter(item => item.id !== key)
//数组中删除多个元素的方法
let a = [1, 4, 8, 10]
let b = [1, 4, 8]
let c = a.filter(item => !b.includes(item))   //[10]
let d = a.slice(3)    //[10]

3.修改使用的也是splice方法和对象的扩展运算符

//splice会改变原数组,它可以实现增删改
//1.增加
arr.splice(index,0,item) //item是想添加的元素,index为数组的索引值,
//2.删除
在方法2中删除已介绍
//3.修改:
const index = newData.findIndex(item => item.key === row.key);
newData.splice(index, 1, {
    
    ...row});
//新的修改方法:
let arr = [{
    
     id: 1, width: 200, height: 200 }]
let obj = {
    
     id: 1, width: 100 }
const index = arr.findIndex(item => item.id == obj.id)
//可以替换原来有的属性,没被替换的继续保留
arr[index] = {
    
     ...arr[index], width: obj.width }

4.查找用的是filter与includes方法

let text = e.target.value
let newData = data.filter(item => {
    
    
  return JSON.stringify(item).toLowerCase().includes(text)                                      
}         

猜你喜欢

转载自blog.csdn.net/m0_48076809/article/details/106313514