RISEBY
核心思想是将数组依据原始位置和新位置”切割“成几部分,调整位置后重新合并,不涉及排序。并且,我给的方案能左移也能右移动。PS. 看到题目变更,目标是数据库,欲哭无泪!var arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];/**
i: 目标元素的index
steps: 移动步数,正数向右移动,负数向左移动
inArray: 目标数组
*/function moveStepsInArray(i, steps, inArray) { if(i<0 || i>inArray.length - 1 || steps === 0) { return inArray;
} var newPosition = i + steps; if(newPosition < 0) { newPosition = 0;
} if(newPosition > inArray.length - 1) { newPosition = inArray.length - 1;
} var front = steps > 0 ? i: newPosition; var after = steps > 0 ? newPosition: i; var targetVal = inArray[i]; if(steps > 0) { return inArray.slice(0, front)
.concat(inArray.slice(front + 1, after + 1))
.concat([targetVal])
.concat(inArray.slice(after + 1))
} if(steps < 0) { return inArray.slice(0, front)
.concat([targetVal])
.concat(inArray.slice(front, after))
.concat(inArray.slice(after + 1));
}
}
moveStepsInArray(4, -3, arr); //将arr中的第4个元素向左移动3步