基于数组的slice()方法实现数据交换位置

摘要

  在使用react配合antd的table组件时,为了实现table数据的上下移动,特地去MDN官网学习了数组的slice()方法的使用。

简单介绍

  slice() 方法返回一个新的数组对象,这一对象是一个由 begin 和 end 决定的原数组的浅拷贝(包括 begin,不包括end)。原始数组不会被改变。

在线编辑demo

  获取当前点击数组的行下标index,使用...扩展运算符配合slice()方法把原始数组重新组合成为一个新的数组,扩展运算符的应用以及slice()方法的配合使用可以在在线编辑器中去尝试。

上移demo

const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
const index = 3;
const newAnimals = [...animals.slice(0, index-1), animals[index], animals[index-1], ...animals.slice(index + 1)]
console.log(animals);
console.log(newAnimals);

  

下移demo

const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
const index =3;
const newAnimals = [...animals.slice(0, index), animals[index+1], animals[index], ...animals.slice(index+2)]
console.log(animals);
console.log(newAnimals);

  

 最后

  在react中配合antd的table的onRow可以获取到当前点击事件行的record数据和index下标,使用slice()方法实现一个可行的上下移动的操作,好了这就是说这次我要分享的东西,如有纰漏,欢迎大家指指点点。

猜你喜欢

转载自www.cnblogs.com/BlueBerryCode/p/11767318.html