简体   繁体   English

如何在不使用库的情况下反转 JavaScript 中的数组?

[英]How can I reverse an array in JavaScript without using libraries?

I am saving some data in order using array s, and I want to add a function that the user can reverse the list.我正在使用array按顺序保存一些数据,我想添加一个用户可以反转列表的功能。 I can't think of any possible method, so if anybody knows how, please help.我想不出任何可能的方法,所以如果有人知道如何,请帮忙。

Javascript has a reverse() method that you can call in an array Javascript 有一个reverse()方法,你可以在数组中调用它

var a = [3,5,7,8];
a.reverse(); // 8 7 5 3

Not sure if that's what you mean by 'libraries you can't use', I'm guessing something to do with practice.不确定这是否是您所说的“您不能使用的库”的意思,我猜这与练习有关。 If that's the case, you can implement your own version of .reverse()如果是这样,您可以实现自己的.reverse()版本

function reverseArr(input) {
    var ret = new Array;
    for(var i = input.length-1; i >= 0; i--) {
        ret.push(input[i]);
    }
    return ret;
}

var a = [3,5,7,8]
var b = reverseArr(a);

Do note that the built-in .reverse() method operates on the original array, thus you don't need to reassign a .请注意,内置的.reverse()方法对原始数组进行操作,因此您不需要重新分配a

Array.prototype.reverse() is all you need to do this work. Array.prototype.reverse()是完成这项工作所需的全部。 See compatibility table .请参阅兼容性表

 var myArray = [20, 40, 80, 100]; var revMyArr = [].concat(myArray).reverse(); console.log(revMyArr); // [100, 80, 40, 20]

Heres a functional way to do it.这是一种实用的方法。

const array = [1,2,3,4,5,6,"taco"];

function reverse(array){
  return array.map((item,idx) => array[array.length-1-idx])
}

20 bytes 20字节

let reverse=a=>[...a].map(a.pop,a)
const original = [1, 2, 3, 4];
const reversed = [...original].reverse(); // 4 3 2 1

Concise and leaves the original unchanged.简明扼要,原汁原味。

reveresed = [...array].reverse()

The shortest reverse method I've seen is this one:我见过的最短的反向方法是这个:

let reverse = a=>a.sort(a=>1)

** **

Shortest reverse array method without using reverse method:不使用逆向法的最短逆向数组法:

** **

 var a = [0, 1, 4, 1, 3, 9, 3, 7, 8544, 4, 2, 1, 2, 3];

 a.map(a.pop,[...a]); 
// returns [3, 2, 1, 2, 4, 8544, 7, 3, 9, 3, 1, 4, 1, 0]

a.pop method takes an last element off and puts upfront with spread operator () a.pop 方法取出最后一个元素并使用扩展运算符 () 放在前面

MDN links for reference: MDN 链接供参考:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/pop https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/pop

two ways:两种方式:

  1. counter loop反循环

    function reverseArray(a) { var rA = [] for (var i = a.length; i > 0; i--) { rA.push(a[i - 1]) } return rA; }
  2. Using.reverse()使用.reverse()

     function reverseArray(a) { return a.reverse() }

This is what you want:这就是你想要的:

array.reverse();

DEMO演示

I've made some test of solutions that not only reverse array but also makes its copy.我已经对解决方案进行了一些测试,这些解决方案不仅可以反转数组,还可以复制它。 Here is test code.这是测试代码。 The reverse2 method is the fastest one in Chrome but in Firefox the reverse method is the fastest. reverse2方法是 Chrome 中最快的方法,但在 Firefox 中, reverse方法是最快的。

var array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

var reverse1 = function() {
  var reversed = array.slice().reverse();
};

var reverse2 = function() {
  var reversed = [];
  for (var i = array.length - 1; i >= 0; i--) {
    reversed.push(array[i]);
  }
};

var reverse3 = function() {
  var reversed = [];
  array.forEach(function(v) {
    reversed.unshift(v);
  });
};

console.time('reverse1');
for (var x = 0; x < 1000000; x++) {
  reverse1();
}
console.timeEnd('reverse1'); // Around 184ms on my computer in Chrome

console.time('reverse2');
for (var x = 0; x < 1000000; x++) {
  reverse2();
}
console.timeEnd('reverse2'); // Around 78ms on my computer in Chrome

console.time('reverse3');
for (var x = 0; x < 1000000; x++) {
  reverse3();
}
console.timeEnd('reverse3'); // Around 1114ms on my computer in Chrome

Here is a version which does not require temp array.这是一个不需要临时数组的版本。

function inplaceReverse(arr) {
  var i = 0;
  while (i < arr.length - 1) {
    arr.splice(i, 0, arr.pop());
    i++;
  }
  return arr;
}

// Useage:
var arr = [1, 2, 3];
console.log(inplaceReverse(arr)); // [3, 2, 1]

53 bytes 53 字节

function reverse(a){
    for(i=0,j=a.length-1;i<j;)a[i]=a[j]+(a[j--]=a[i++],0)
}

Just for fun, here's an alternative implementation that is faster than the native .reverse method.只是为了好玩,这里有一个比原生.reverse方法更快的替代实现。

You can do你可以做

var yourArray = ["first", "second", "third", "...", "etc"]
var reverseArray = yourArray.slice().reverse()

console.log(reverseArray)

You will get你会得到

["etc", "...", "third", "second", "first"]
> var arr = [1,2,3,4,5,6];
> arr.reverse();
  [6, 5, 4, 3, 2, 1]
array.reverse() 

Above will reverse your array but modifying the original.以上将反转您的数组但修改原始数组。 If you don't want to modify the original array then you can do this:如果您不想修改原始数组,那么您可以这样做:

var arrayOne = [1,2,3,4,5];

var reverse = function(array){
    var arrayOne = array
    var array2 = [];

    for (var i = arrayOne.length-1; i >= 0; i--){
      array2.push(arrayOne[i])
    } 
    return array2
}

reverse(arrayOne)
function reverseArray(arr) {
    let reversed = [];
    for (i = 0; i < arr.length; i++) { 
    reversed.push((arr[arr.length-1-i]))
    }
  return reversed;
}

Using.pop() method and while loop.使用.pop() 方法和 while 循环。

var original = [1,2,3,4];
var reverse = [];
while(original.length){
    reverse.push(original.pop());
}

Output: [4,3,2,1]输出:[4,3,2,1]

I'm not sure what is meant by libraries, but here are the best ways I can think of:我不确定图书馆是什么意思,但这是我能想到的最佳方式:

// return a new array with .map()
const ReverseArray1 = (array) => {
    let len = array.length - 1;

    return array.map(() => array[len--]);
}

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

// initialize and return a new array
const ReverseArray2 = (array) => {
    const newArray = [];
    let len = array.length;

    while (len--) {
        newArray.push(array[len]);
    }

    return newArray;
}

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

// use swapping and return original array
const ReverseArray3 = (array) => {
    let i = 0;
    let j = array.length - 1;

    while (i < j) {
        const swap = array[i];
        array[i++] = array[j];
        array[j--] = swap;
    }

    return array;
}
console.log(ReverseArray3([1,2,3,4,5]))//[5,4,3,2,1]

// use .pop() and .length
const ReverseArray4 = (array) => {
    const newArray = [];

    while (array.length) {
        newArray.push(array.pop());
    }

    return newArray;
}
console.log(ReverseArray4([1,2,3,4,5]))//[5,4,3,2,1]

Pure functions to reverse an array using functional programming:使用函数式编程反转数组的纯函数:

var a = [3,5,7,8];

// ES2015
function immutableReverse(arr) {
  return [ ...a ].reverse();
}

// ES5
function immutableReverse(arr) {
  return a.concat().reverse()
}

As others mentioned, you can use .reverse() on the array object.正如其他人提到的,您可以在数组对象上使用.reverse()

However if you care about preserving the original object , you may use reduce instead:但是,如果您关心保留原始对象,则可以改用reduce

const original = ['a', 'b', 'c'];
const reversed = original.reduce( (a, b) => [b].concat(a) );
//                                           ^
//                                           |
//                                           +-- prepend b to previous accumulation

// original: ['a', 'b', 'c'];
// reversed: ['c', 'b', 'a'];

It can also be achieved using map method.也可以使用map方法来实现。

[1, 2, 3].map((value, index, arr) => arr[arr.length - index - 1])); // [3, 2, 1]

Or using reduce (little longer approach)或者使用 reduce (稍微长一点的方法)

[1, 2, 3].reduce((acc, curr, index, arr) => {
    acc[arr.length - index - 1] = curr;
    return acc;
}, []);

reverse in place with variable swapping (mutative)通过变量交换(可变)就地反转

const myArr = ["a", "b", "c", "d"];
for (let i = 0; i < (myArr.length - 1) / 2; i++) {  
    const lastIndex = myArr.length - 1 - i; 
    [myArr[i], myArr[lastIndex]] = [myArr[lastIndex], myArr[i]] 
}

Reverse by using the sort method使用sort方法反转

  • This is a much more succinct method.这是一种更简洁的方法。

 const resultN = document.querySelector('.resultN'); const resultL = document.querySelector('.resultL'); const dataNum = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; const dataLetters = ['a', 'b', 'c', 'd', 'e']; const revBySort = (array) => array.sort((a, b) => a < b); resultN.innerHTML = revBySort(dataNum); resultL.innerHTML = revBySort(dataLetters);
 <div class="resultN"></div> <div class="resultL"></div>

Using ES6 rest operator and arrow function.使用 ES6 剩余运算符和箭头函数。

const reverse = ([x, ...s]) => x ? [...reverse(s), x] : [];
reverse([1,2,3,4,5]) //[5, 4, 3, 2, 1]

Use swapping and return the original array.使用交换并返回原始数组。

 const reverseString = (s) => { let start = 0, end = s.length - 1; while (start < end) { [s[start], s[end]] = [s[end], s[start]]; // swap start++, end--; } return s; }; console.log(reverseString(["s", "t", "r", "e", "s", "s", "e", "d"]));

Infact the reverse() may not work in some cases, so you have to make an affectation first as the following实际上reverse()在某些情况下可能不起作用,所以你必须先做一个如下的做作

let a = [1, 2, 3, 4];
console.log(a);  // [1,2,3,4]
a = a.reverse();
console.log(a); // [4,3,2,1]

or use concat或使用连接

let a = [1, 2, 3, 4];
console.log(a, a.concat([]).reverse());  // [1,2,3,4], [4,3,2,1]

What about without using push() !不使用 push() 怎么办!

Solution using XOR !使用 XOR 的解决方案

var myARray = [1,2,3,4,5,6,7,8];

function rver(x){
    var l = x.length;
    for(var i=0; i<Math.floor(l/2); i++){

        var a = x[i];
        var b = x[l-1-i];

        a = a^b;
        b = b^a;
        a = a^b;

        x[i] = a;
        x[l-1-i] = b;
    }

    return x;

}

console.log(rver(myARray));

JavaScript already has reverse() method on Array, so you don't need to do that much! JavaScript 在 Array 上已经有 reverse() 方法,所以你不需要做那么多!

Imagine you have the array below:假设您有以下数组:

var arr = [1, 2, 3, 4, 5];

Now simply just do this:现在只需这样做:

arr.reverse();

and you get this as the result:结果是:

[5, 4, 3, 2, 1];

But this basically change the original array, you can write a function and use it to return a new array instead, something like this:但这基本上改变了原始数组,您可以编写一个函数并用它返回一个新数组,如下所示:

function reverse(arr) {
  var i = arr.length, reversed = [];
  while(i) {
    i--;
    reversed.push(arr[i]);
  }
  return reversed;
}

Or simply chaning JavaScript built-in methods for Array like this:或者像这样简单地改变 Array 的 JavaScript 内置方法:

function reverse(arr) {
  return arr.slice().reverse();
}

and you can call it like this:你可以这样称呼它:

reverse(arr); //return [5, 4, 3, 2, 1];

Just as mentioned, the main difference is in the second way, you don't touch the original array...如前所述,主要区别在于第二种方式,您不接触原始数组...

How about this?:这个怎么样?:

  function reverse(arr) {
    function doReverse(a, left, right) {
      if (left >= right) {
        return a;
      }
      const temp = a[left];
      a[left] = a[right];
      a[right] = temp;
      left++;
      right--;
      return doReverse(a, left, right);
    }

    return doReverse(arr, 0, arr.length - 1);
  }

  console.log(reverse([1,2,3,4]));

https://jsfiddle.net/ygpnt593/8/ https://jsfiddle.net/ygpnt593/8/

This function will work with arrays that may have gaps between their indices.此函数适用于索引之间可能存在间隙的数组。

function reverse( a ) {
    var b = [], c = [] ;
    a.forEach( function( v ) { b.push( v ) } ) ;
    a.forEach( function( v, i ) { c[i] = b.pop() } ) ;
    return c ;
}

var a= [] ; a[1] = 2 ; a[3] = 4 ; a[7] = 6 ; a[9] = 8 ;
a = reverse( a ) ;
var s = '' ;
a.forEach( function( v, i ) { s += 'a[' + i + '] = ' + v + '  ' } ) ;
console.log( s ) ;
// a[1] = 8  a[3] = 6  a[7] = 4  a[9] = 2

Below is a solution with best space and time complexity以下是具有最佳空间和时间复杂度的解决方案

function reverse(arr){
let i = 0;
let j = arr.length-1; 
while(i<j){
arr[j] = arr[j]+arr[i];
arr[i] = arr[j] - arr[i];
arr[j] = arr[j] - arr[i];
i++;
j--;
}
return arr;
}
var arr = [1,2,3,4,5,6,7,8,9]
reverse(arr);

output => [9,8,7,6,5,4,3,2,1]输出 => [9,8,7,6,5,4,3,2,1]

reverse array and sub-array (in place) with ES6.使用 ES6 反转数组和子数组(就地)。

function reverse(array, i=0, j=array.length-1){
  while (i < j){
    [array[i], array[j]] = [array[j], array[i]];
    ++i;
    --j;
  }
}

We have reverse() function to reverse the given array in JS.我们有 reverse() 函数来反转 JS 中给定的数组。

var a = [7,8,9];
a.reverse(); // 9 8 7

function reverseArr(input) 
{
var ret = new Array;
for(var i = input.length-1; i >= 0; i--) 
{
    ret.push(input[i]);
}
return ret;
}

I also faced the same problem.我也遇到了同样的问题。 Thank you for this question.谢谢你提出这个问题。 I did the code like the below snippet.我做了如下代码片段的代码。 It works nicely.它工作得很好。 I used ES6.我用的是 ES6。

const Array = ["a", "b", "c", "d"];
let revArray = [].concat(Array).reverse();

when I console.log it I got the output like below当我 console.log 它时,我得到如下输出

console.log(revArray)
// output: ["d","c","b","a"]

I just rewrote the haskell implementation to js.我只是将haskell实现重写为js。

const rev = (list, reversed) => {
    if (list.length == 0) return reversed

    reversed.unshift(list[0])
    return rev(list.slice(1), reversed)
}

const reverse = (list) => rev(list, [])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在没有.reverse() 的情况下反转 javaScript 中的数组 - How do i reverse an array in javaScript without .reverse() javascript 在不使用 reverse() 的情况下反转数组 - javascript reverse an array without using reverse() 如何在 Javascript 中反转 object 的数组? - How can I reverse an array of object in Javascript? 如何仅使用没有库的javascript从同一个类的不同div获取值的总和? - How can I get sum of values from different divs with the same class using only javascript without libraries? 在不使用数组的情况下反转 JavaScript 中的字符串 - Reverse a string in JavaScript without using an array 如何在没有 Array.prototype.reverse 的情况下反转 JavaScript 中的数组? - How to reverse an array in JavaScript without Array.prototype.reverse? 如何在没有 .reverse() 的情况下反转 16 个或更少字符的 JavaScript 数组? - How do I reverse an array in JavaScript in 16 characters or less without .reverse()? 如何使用bing通过bing反向地址解析? - How can I reverse geocode through bing using javascript? 如何在不使用javascript擦除数组中以前的值的情况下将值添加到数组中? - how can I add values into an array without erasing previous values in array using javascript? 如何反转 Javascript 中的数组? - How to reverse an array in Javascript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM