反转数组而不“反转"或复制数组

编程入门 行业动态 更新时间:2024-10-22 23:39:59
本文介绍了反转数组而不“反转"或复制数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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).

更多推荐

反转数组而不“反转"或复制数组

本文发布于:2023-06-04 08:34:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/493340.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   而不   quot

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!