如何在react和/或javascript中手动排序(移动)数组元素?
假设我有这个数组如何在react和/或javascript中手动排序(移动)数组元素?,javascript,reactjs,Javascript,Reactjs,假设我有这个数组 arr = ["me", "you", "us", "them"] 我希望能够在单击每个数组元素时将其向上移动一个索引, e、 g当我点击“他们”时,数组应该是这样的 arr = ["me", "you", "them", "us" ] 我想使用splice()。这是我的密码 moveRowUp = (to, frm) => { const {layout} = this.state if(to >= layout.length){
arr = ["me", "you", "us", "them"]
我希望能够在单击每个数组元素时将其向上移动一个索引,
e、 g当我点击“他们”时,数组应该是这样的
arr = ["me", "you", "them", "us" ]
我想使用splice()。这是我的密码
moveRowUp = (to, frm) => {
const {layout} = this.state
if(to >= layout.length){
let diff = to - layout.length;
while((diff--) + 1){
layout.push(undefined)
}
}
layout.splice(to, 0, layout.splice(to, 1)[0]);
// this.setState({
// layout: layout
// })
}
与其使用拼接,不如交换两个值
function moveUp(arr, index) {
if (index > 0) {
_swap(arr, index, index - 1);
}
}
function moveDown(arr, index) {
if (index < arr.length - 1) {
_swap(arr, index, index + 1);
}
}
function _swap(obj, prop1, prop2) {
var tmp = obj[prop1];
obj[prop1] = obj[prop2];
obj[prop2] = tmp;
}
函数上移(arr,索引){
如果(索引>0){
_掉期(arr,指数,指数-1);
}
}
函数向下移动(arr,索引){
如果(索引
这将是我使用拼接的方法
const words=['first','second','third'];
功能点击(一){
如果(i
.as控制台包装{最大高度:100%!重要;顶部:0;}
示例:
const a=[“我”、“你”、“我们”、“他们”];
const moveLeft=arr=>word=>{
常数i=arr.indexOf(word);
如果(i>-1){
阵列拼接(i,1);
arr.splice((i!==0)?i-1:arr.length,0,word)//句柄0索引
}
返回a;
}
console.log(moveLeft(a)('them'))
为什么不发布您试图实现这一点的代码?笑得很开心@andreas@HimanshuTyagi我刚刚用我的代码编辑和更新了您只需要简单的交换就可以实现这一点。互换(项目,项目1)