# JavaScript数组反转教程

## 如何使用Reverse方法反转JavaScript中的数组

``````let numbers = [1, 2, 3, 4, 5];
let reversedNumbers = numbers.reverse();

console.log(reversedNumbers);
// [5, 4, 3, 2, 1]``````

``````let numbers = [1, 2, 3, 4, 5];
let reversedNumbers = numbers.reverse();

console.log(reversedNumbers);
// [5, 4, 3, 2, 1]

console.log(numbers);
// [5, 4, 3, 2, 1]``````

``[...numbers]``

``````let numbers = [1, 2, 3, 4, 5];
let reversedNumbers = [...numbers].reverse();

console.log(reversedNumbers);
// [5, 4, 3, 2, 1]

console.log(numbers);
// [1, 2, 3, 4, 5]``````

## 如何使用Slice和Reverse方法反转JavaScript中的数组

`slice` 方法用于将所选元素作为新数组返回，当你调用不带任何参数的方法时，它将返回一个与原始数组相同的新数组（从第一个元素到最后一个元素）。

``````let numbers = [1, 2, 3, 4, 5];
let reversedNumbers = numbers.slice().reverse();

console.log(reversedNumbers);
// [5, 4, 3, 2, 1]

console.log(numbers);
// [1, 2, 3, 4, 5]``````

## 如何在没有Reverse方法的情况下在JavaScript中反转数组

``````let numbers = [1, 2, 3, 4, 5];
let reversedNumbers = [];

for(let i = numbers.length -1; i >= 0; i--) {
reversedNumbers.push(numbers[i]);
}

console.log(reversedNumbers);``````

## 如何用JS编写自己的反转函数

``````function customReverse(originalArray) {
let leftIndex = 0;
let rightIndex = originalArray.length - 1;
}``````

``````while (leftIndex < rightIndex) {
// 交换元素
let temp = originalArray[leftIndex];
originalArray[leftIndex] = originalArray[rightIndex];
originalArray[rightIndex] = temp;
}``````

`````` function customReverse(originalArray) {

let leftIndex = 0;
let rightIndex = originalArray.length - 1;

while (leftIndex < rightIndex) {

// 用temp变量交换元素
let temp = originalArray[leftIndex];
originalArray[leftIndex] = originalArray[rightIndex];
originalArray[rightIndex] = temp;

// 将索引移到中间
leftIndex++;
rightIndex--;
}
}``````

``````let myArray = [1, 2, 3, 4, 5];

customReverse(myArray);

console.log(myArray);

// output is [5, 4, 3, 2, 1]``````

11k 声望
5.6k 粉丝