我正在尝试解决以下练习:
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).
更多推荐
反转数组而不“反转"或复制数组
发布评论