js如何让数组中的相邻两个对象上移下移
时间: 2023-08-08 14:02:07 浏览: 57
在 JavaScript 中,可以使用数组的 `splice()` 方法来实现数组中相邻对象的上移和下移。下面是示例代码:
上移相邻两个对象:
```javascript
function moveUp(arr, index) {
if (index > 0 && index < arr.length) { // 确保对象在数组范围内
const temp = arr[index - 1];
arr[index - 1] = arr[index];
arr[index] = temp;
}
}
const myArray = [1, 2, 3, 4, 5];
const targetIndex = 2; // 对象所在的索引
moveUp(myArray, targetIndex);
console.log(myArray); // 输出:[1, 2, 4, 3, 5]
```
下移相邻两个对象:
```javascript
function moveDown(arr, index) {
if (index >= 0 && index < arr.length - 1) { // 确保对象在数组范围内
const temp = arr[index + 1];
arr[index + 1] = arr[index];
arr[index] = temp;
}
}
const myArray = [1, 2, 3, 4, 5];
const targetIndex = 2; // 对象所在的索引
moveDown(myArray, targetIndex);
console.log(myArray); // 输出:[1, 2, 4, 3, 5]
```
以上代码示例中,`moveUp()` 函数将给定索引的对象和其前一个对象进行交换,实现了上移操作。`moveDown()` 函数将给定索引的对象和其后一个对象进行交换,实现了下移操作。