反转数组而不“反转"或复制数组 [英] Reversing an array without 'reverse' or duplicating an array

查看:34
本文介绍了反转数组而不“反转"或复制数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试解决以下练习:

I'm trying to solve the following exercise:

不使用reverse方法反转数组,不使用a第二个数组,并且不复制任何值.

Reverse an array without using the reverse method, without using a second array, and without duplicating any of the values.

我曾考虑将数组设为对象,然后从头到尾更新数组,但我认为您也可以更新它.

I've thought about making the array an object and then updating the array from the end to the beginning but I figured you can just update it as well.

尝试了一些简单的方法:

Tried something simple like:

function reverseArray(array) {
  for (var i = 0; i < array.length; i++) {
    // var elem = array.shift();
    var elem = array.shift()
    array.push(elem)
  }
  return array
}

array = ['a', 'b','c','d','e'];

reverseArray(array);

但这并没有真正改变它.有关如何执行此操作的任何建议或解释?

But that doesn't really change it. Any advice or explanation on how to do this?

推荐答案

使用 ES6 语法,您不需要将值复制到临时变量中(这是最后一个要求吗?).

With ES6 syntax you don't need to copy a value into a temporary variable (is that what the last requirement is about?).

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

const arr = ['a','b','c','d','e'];
reverse(arr);
console.log(arr);

有人可能会争辩说数组是在这里创建的(如果引擎不优化它),就像 splice 也创建一个数组(作为它的返回值)一样.

One may argue that arrays are created here (if engines don't optimise this away), just like splice also creates an array (as its return value).

这篇关于反转数组而不“反转"或复制数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆