JavaScript:反转数组的三种方法

时间:2024-10-19 14:46:19

Reversing an array in different ways is one of the most popular questions you can expect to get at a JavaScript interview. In this article, I will present three ways to reverse an array, and using a built-in reverse method is not going to be one of them. This method reverses an array by modifying it, which means the first element in the original array becomes the last element and the last one becomes the first. An array can be reversed by both modifying the original array or without changing the original array.

[R eversing以不同的方式数组是你可以期望获得在JavaScript的采访中最流行的问题之一。 在本文中,我将介绍三种反转数组的方法,而使用内置的reverse方法将不是其中一种。 此方法通过修改数组来反转数组,这意味着原始数组中的第一个元素成为最后一个元素,而最后一个成为第一个元素。 可以通过修改原始数组或不更改原始数组来反转数组。

The first two solutions that I will share below will be examples of reversing an array without mutating the original array and the last one will demonstrate how to reverse an array by modifying the original array.

我下面将分享的前两个解决方案是在不更改原始数组的情况下反转数组的示例,最后一个将演示如何通过修改原始数组来反转数组。